首页 > 解决方案 > JAVA中JsonObjects的JsonObject

问题描述

我有一个JSONObject完整的JSONobjects,我需要将它们中的每一个提取到一个新的中JSONObject,以便我可以单独操作它们中的每一个,但我真的不知道该怎么做。我的代码是这样的:

public void loadBodies(InputStream in) {

JSONObject jsonInput= new JSONObject(new JSONTokener(in));

JSONObject jo2 = jsonInput.getJSONObject("bodies"); //probably incorrect
for(JSonObject j: jo2) b.create(j); //i need to apply the create method to all the JSONObjects

想象这样的 JSON

{'bodies': [
        {
            'total': 142250.0, 
            '_id': 'BC'
        }, 
        {
            'total': 210.88999999999996,
             '_id': 'USD'
        }, 

        {
            'total': 1065600.0, 
            '_id': 'TK'
        }
        ]
}

我需要将JSONObject键下的所有 s提取bodies到一个新的集合中JSONObjects,以便我可以对它们进行操作。所以基本上,循环提取它们,但我不知道如何。

标签: javajsonloops

解决方案


根据您的示例,bodies是一个 JSON 数组。所以使用JSONArrayorg.json:json来迭代数组的内容:

String     json      = "{\"bodies\": [{\"total\": 142250.0, \"_id\": \"BC\"}]}";

JSONObject jsonInput = new JSONObject(new JSONTokener(new StringReader(json)));
JSONArray  array     = jsonInput.getJSONArray("bodies");
for (int i = 0; i < array.length(); i++) {
    JSONObject obj = array.getJSONObject(i);
     // implement here your logic on obj
}

推荐阅读