简体   繁体   中英

JsonObject of JsonObjects in JAVA

I have a JSONObject full of JSONobject s, and I need to extract each of those into a new JSONObject so I can manipulate each of them individually, but I don't really know how to do it. My code is like this:

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

imagine the JSON like this

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

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

I need to extract all the JSONObject s under the key bodies into a new set of JSONObjects , so I can operate with them. So basically, extract them in a loop, but I don't know how to.

According to your example, bodies is a JSON array. So use JSONArray of the org.json:json library in order to iterate over the array's content:

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
}

You can do like this and manipulate each value according to your requirement . This method calls recursively every time when it finds any JSONObject or JSONArray inside object. handleValue() method for manipulating value for specific key.

public void handleJSON(Object input, Map<String,Object> result ){
if (input instanceof JSONObject) {
  List < String > keys = new ArrayList < > (((JSONObject) input).keySet());
  for (String key: keys) {
    if (!(((JSONObject) input).get(key) instanceof JSONArray))
      if (((JSONObject) input).get(key) instanceof JSONObject) {
        handleJSONObject(((JSONObject) input).get(key), map);
      } else {
        Object value = ((JSONObject) input).get(key);
        ((JSONObject) input).put(key, handleValue(value, map));
      }
    else
      handleJSONObject(new JSONArray(((JSONObject) input).get(key).toString()), map);
  }

}
if (input instanceof JSONArray) {
  for (int i = 0; i < ((JSONArray) input).length(); i++) {
    JSONObject jsonObject = ((JSONArray) input).getJSONObject(i);
    handleJSONObject(jsonObject, map);
  }
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM