Java JSON 解析数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17191135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:15:56  来源:igfitidea点击:

Java JSON parse array

javajson

提问by Ping

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

谢谢

回答by roger_that

Try using org.json.simple.parser.JSONParserSomething like this:

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

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 servicesis a JSONArray, so fetch it in JSONArray. Like this:

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

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

Now, you can iterate through this servicesJSONArray as well.

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

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.

希望这能解决您的问题。

回答by chetan

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

回答by Ping

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

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

Reading JSON

读取 JSON

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

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

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

Access the contents of a JSON object:

访问 JSON 对象的内容:

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

Access the contents of a JSON array:

访问 JSON 数组的内容:

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