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

4

3 回答 3

1

尝试使用这样的org.json.simple.parser.JSONParser 东西:

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

现在要访问这些字段,您可以这样做:

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

Andservices是一个 JSONArray,所以在 JSONArray 中获取它。像这样:

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

现在,您也可以遍历这个servicesJSONArray。

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

希望这能解决你的问题。

于 2013-06-19T12:54:29.790 回答
0

我用https://github.com/ralfstx/minimal-json解决了这个问题

读取 JSON

从 Reader 或 String 读取 JSON 对象或数组:

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

访问 JSON 对象的内容:

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

访问 JSON 数组的内容:

String name = jsonArray.get( 0 ).asString();
int age = jsonArray.get( 1 ).asInt(); // asLong(), asFloat(), asDouble(), ...
于 2013-06-19T13:48:33.877 回答
0

为什么需要解析器?尝试这个:-

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());
于 2013-06-19T13:14:19.760 回答