Java从JSON Array中提取数据

时间:2018-05-18 08:32:19

标签: java arrays json

下面是json格式,我必须提取动态键值对的数据。

{"data": [
         {"1000":"2018-03-10 00:00:00.0"},
         {"100031": "2018-03-15"}
         ]
}

这是我正在尝试但它不起作用并显示错误:

在输入中,我得到了JSON对象。

JSONArray lastdtArr =   json.getJSONArray("data");
int len = lastdtArr.length();
for(int i=0;i<len;i++) {
    JSONObject lastdtid = lastdtArr.getJSONObject(i);
    int id = lastdtid.getKey();
    String date = lastdtid.getValue();
    //Operations to perform
}

PS:我是Java新手。我在互联网上找到的解决方案是针对json格式,其中密钥在键值对中被修复。但在这种情况下,关键始终是动态的。请告诉我在循环中我要写的是什么以获取id和date中的值?

1 个答案:

答案 0 :(得分:0)

你需要使用JSONArray来提取你的数据,因为它是一个OBJECT的ARRAY,然后你可以使用JSONObject迭代它来访问这个数组中的每个对象,这是我几个月前写的快速指南:

What is a JSON object : (just to be clear) A .json file contains text-based representations of data structures and objects. A JSON object is delimited by "{" and "}" and represent a single object/structure inside a .json file.

JSONObject : It's a type representing a single JSON object in JAVA.

JSONArray : Seems obvious, but it's an array wich contains JSONObject elements, 
            i recommend you to use this to keep your objects packed into an array,
            this type is providing a lot of usefull methods aswell as JSONObject does,
            i'll list some of them below it's up to you to search for the others. 

JSONArray.getJSONObject(index) : Pass it an index and it will return the JSONObject stored 
                                 at this index.
JSONArray.put([value] | [index, value]) : This might be extremly straightforward but it's actually pretty 
                       usefull if you want to build a JSONArray, pass it a JSONObject 
                       or another common type (int, String, etc) and it will add it to 
                       your JSONArray. 
                       Depending on what you pass it you'll need an index aswell.

JSONObject.keys() : Returns an iterator of the String names in your JSONObject.

JSONObject.put(name, value) : Create a field in your JSONObject using the name you passed 
                              and assigning the value to it.

JSONObject.getString(name) : Pass the name of a field to it and it will return 
                             it's value as a String. As you may have guess already, there is a couple of those, not only getString().

其余由你决定。