2

I am using the following library to parse an object:

{"name": "web", "services": []}

And the following code

import com.json.parsers.JSONParser;


JSONParser parser = new JSONParser();
Object obj = parser.parseJson(stringJson);

when the array services is empty, it displays the following error

@Key-Heirarchy::root/services[0]/   @Key::  Value is expected but found empty...@Position::29

if the array services has an element everything works fine

{"name": "web", "services": ["one"]}

How can I fix this?

Thanks

2
  • 4
    Step 1: use jackson wiki.fasterxml.com/JacksonHome Step 2: Thank me later. Commented Jun 19, 2013 at 12:32
  • +1 for Jackson. Drop-dat-lib. Commented Jun 19, 2013 at 13:16

3 Answers 3

1

Try using org.json.simple.parser.JSONParser Something like this:

JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(stringJson);

Now to access the fields, you can do this:

JSONObject name = jsonObject.get("name"); //gives you 'web'

And services is a JSONArray, so fetch it in JSONArray. Like this:

JSONArray services = jsonObject.get("services");

Now, you can iterate through this services JSONArray as well.

Iterator<JSONObject> iterator = services.iterator();
// iterate through json array
 while (iterator.hasNext()) {
   // do something. Fetch fields in services array.
 }

Hope this would solve your problem.

Sign up to request clarification or add additional context in comments.

Comments

0

Why do you need parser? try this:-

String stringJson = "{\"name\": \"web\", \"services\": []}";
JSONObject obj = JSONObject.fromObject(stringJson);
System.out.println(obj);
System.out.println(obj.get("name"));
System.out.println(obj.get("services"));
JSONArray arr = obj.getJSONArray("services");
System.out.println(arr.size());

Comments

0

I solve the problen with https://github.com/ralfstx/minimal-json

Reading JSON

Read a JSON object or array from a Reader or a String:

JsonObject jsonObject = JsonObject.readFrom( jsonString );
JsonArray jsonArray = JsonArray.readFrom( jsonReader );

Access the contents of a JSON object:

String name = jsonObject.get( "name" ).asString();
int age = jsonObject.get( "age" ).asInt(); // asLong(), asFloat(), asDouble(), ...

Access the contents of a JSON array:

String name = jsonArray.get( 0 ).asString();
int age = jsonArray.get( 1 ).asInt(); // asLong(), asFloat(), asDouble(), ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.