简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM