json对象到Java中的多个json数组

时间:2018-05-10 11:21:46

标签: java json

嗨,我有一个奇怪的问题,任何人都可以帮助我。

我有一个像

这样的json对象
{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
  "key4": [{
    "key5":"value5",
    "key6":"value6"
  },
  {
    "key7":"value7",
    "key8":"value8"
  },{
    "key9":"value9",
    "key0":"value0"
  }]
}

我希望将上面的json转换为下面提到的json数组。

[{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
  "key5":"value5",
  "key6":"value6"
},
{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
  "key7":"value7",
  "key8":"value8"
},{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
  "key9":"value9",
  "key0":"value0"
}]

由于第1对,第2对和第3对是相同的,因此它们需要在所有对象中都是通用的。请提供以上

的一些想法

1 个答案:

答案 0 :(得分:0)

您可以使用JSONObject& JSONArray,请尝试以下代码:

public static void main(String[] args) {
    // TODO Auto-generated method stub

      // INIT
      JSONObject obj = new JSONObject();
      JSONObject obj56 = new JSONObject();
      JSONObject obj78 = new JSONObject();
      JSONObject obj90 = new JSONObject();
      JSONArray list = new JSONArray();

      obj56.put("key5", "value5");
      obj56.put("key6", "value6");
      obj78.put("key7", "value7");
      obj78.put("key8", "value8");
      obj90.put("key9", "value9");
      obj90.put("key0", "value0");

      list.put(obj56);
      list.put(obj78);
      list.put(obj90);

      obj.put("key1", "value1");
      obj.put("key2", "value2");
      obj.put("key3", "value3");
      obj.put("key4", list);

      // PROC
      JSONArray newjsonarr = new JSONArray();
      HashMap<String,String> hmpkeys=new HashMap<String,String>();  
      Iterator<String> keysItr = obj.keys();
      while (keysItr.hasNext()) {
          String key = keysItr.next();
          Object value = obj.get(key);
          if (value instanceof JSONArray) {
              for(int i = 0; i<((JSONArray) value).length();i++){
                  JSONObject mycurrentObject = ((JSONArray) value).getJSONObject(i);
                  HashMap<String, String> map3 = new HashMap<String, String>(hmpkeys);
                  map3.putAll(JonToMap(mycurrentObject));
                  newjsonarr.put(HmapToJon(map3));
              } 
          } else {
              hmpkeys.put(key, value.toString());
          }
      }

      System.out.println(newjsonarr);
}

// HELPERS
public static HashMap<String,String>  JonToMap(JSONObject myObject){
   HashMap<String,String> hm=new HashMap<String,String>();
   Iterator<String> keysItr = myObject.keys();
   while (keysItr.hasNext()) {
          String key = keysItr.next();
          Object value = myObject.get(key);
          hm.put(key, value.toString());
   }
   return hm;
}

public static JSONObject HmapToJon(HashMap<String,String> hm){
    // play with java8 
    JSONObject jsonobj = new JSONObject();
    hm.forEach((k,v)->jsonobj.put(k,v));
    return jsonobj;
}