java JSON:获取 JSON 对象列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32252606/
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-02 19:54:02  来源:igfitidea点击:

JSON: Get list of JSON Objects

javajson

提问by wwjdm

In java how can I pull out the JSON objects enclosed in the "{}"?

在 java 中,如何提取包含在“{}”中的 JSON 对象?

I have tried:

我努力了:

JSONObject obj = new JSONObject(jstring);
obj.getJSONArray("fileName");

But it only return the first object. How do I get a list with both objects?

但它只返回第一个对象。如何获取包含两个对象的列表?

JSON:

JSON:

[
{
    "fileName": [
        "file1"
    ],
    "date": [
        "8/25/2015 0:00"
    ],
    "time": [
        "7/16/2009 16:51"
    ],
    "id": "1",
    "version_": 1
},
{
    "fileName": [
        "file1"
    ],
    "date": [
        "8/25/2015 0:00"
    ],
    "time": [
        "7/16/2009 16:51"
    ],
    "id": "1",
    "version_": 1
}
]

回答by Mauker

Your root JSON is an Array, so first create a JSONArrayfrom your String.

您的根 JSON 是一个数组,因此首先JSONArray从您的String.

Do this:

做这个:

JSONArray arr = new JSONArray(jstring);
for (int i = 0; i < arr.length(); i++) { // Walk through the Array.
    JSONObject obj = arr.getJSONObject(i);
    JSONArray arr2 = obj.getJSONArray("fileName");
    // Do whatever.
}

For more info, please refer to the docs on JSONArrayand JSONObject.

欲了解更多信息,请参阅文档上的JSONArrayJSONObject

回答by Pavel Gatnar

You have to directly construct JSONArray from JSON string in this case.

在这种情况下,您必须直接从 JSON 字符串构造 JSONArray。

JSONArray arr = new JSONArray(jstring);

回答by Simimmo

JSONArray jsonArray = new JSONArray(jstring);