Ping
Ping

Reputation: 31

Java JSON parse array

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

Upvotes: 2

Views: 14209

Answers (3)

Ping
Ping

Reputation: 31

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(), ...

Upvotes: 0

chetan
chetan

Reputation: 2886

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());

Upvotes: 0

roger_that
roger_that

Reputation: 9791

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.

Upvotes: 1

Related Questions