JAVA中JsonObjects的JsonObject

时间:2019-03-03 23:48:59

标签: java json loops

我有一个JSONObject的{​​{1}}装满,我需要将它们中的每一个都提取到一个新的JSONobject中,这样我才能分别操作它们,但是我没有真的知道该怎么做。我的代码是这样的:

JSONObject

想象这样的JSON

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

我需要将键{'bodies': [ { 'total': 142250.0, '_id': 'BC' }, { 'total': 210.88999999999996, '_id': 'USD' }, { 'total': 1065600.0, '_id': 'TK' } ] } 下的所有JSONObject提取到一组新的bodies中,以便可以对其进行操作。所以基本上,将它们循环提取,但我不知道该怎么做。

2 个答案:

答案 0 :(得分:0)

根据您的示例,bodies是一个JSON数组。因此,请使用JSONArray库的org.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
}

答案 1 :(得分:0)

您可以这样做并根据您的要求操作每个值。每次在对象中找到任何 JSONObject 或 JSONArray 时,此方法都会递归调用。 handleValue() 方法,用于操作特定键的值。

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