2017-04-21 32 views
1

輸入:JSON來JSON

{ 
    "Student": { 
     "name" :"abc", 
     "id" : 588, 
     "class : "12" 
    } 
} 

Reqired輸出:

{ 
    "Student": { 

     "key" :"name", 
     "value":"abc", 

     "key" :"id", 
     "value":"588", 

     "key" :"class", 
     "value":"12" 
    } 
} 
+0

請檢查我的答案。 – ozgur

回答

2

你的輸出JSON無效。 Json對象不能重複鍵。

您可以使用庫org.json,做這樣的事情:

JSONObject jsonObject = new JSONObject(inputJson); 
    JSONObject outputJson = new JSONObject(); 
    JSONArray array = new JSONArray(); 

    for (Object key : jsonObject.keySet()) { 
     JSONObject item = new JSONObject(); 

     String keyStr = (String)key; 
     Object keyvalue = jsonObj.get(keyStr); 
     item.put(keyStr, keyvalue); 
     array.put(item); 

    } 
    outputJson.put("Student", array); 
    System.out.println(json.toString()); 

輸出:

{ 
    "Student": [ 

     { 
      "key": "name", 
      "value": "abc" 
     }, 

     { 
      "key": "id", 
      "value": "588" 
     }, 
     { 
      "key": "class", 
      "value": "12" 
     } 
    ] 

} 
0

到對方的回答一樣,所需的輸出JSON格式無效。

最接近的有效產出將是

{ 
    "Student" : [ { 
    "key" : "name", 
    "value" : "abc" 
    }, { 
    "key" : "id", 
    "value" : 588 
    }, { 
    "key" : "class", 
    "value" : "12" 
    } ] 
} 

這可以通過顛簸產生具有以下規格

[ 
    { 
    "operation": "shift", 
    "spec": { 
     "Student": { 
     "name": { 
      "$": "Student[0].key", 
      "@": "Student[0].value" 
     }, 
     "id": { 
      "$": "Student[1].key", 
      "@": "Student[1].value" 
     }, 
     "class": { 
      "$": "Student[2].key", 
      "@": "Student[2].value" 
     } 
     } 
    } 
    } 
]