我正在尝试在JSON结构中重组重复的json值,并使用最简单的方法重新排列它们。
我到了每次循环遍历JSONObject时都设法将其存储在映射中的地步,但是从此处如何继续存储映射以实现所需的结果?提前非常感谢您。
public static void main(String[] args) throws JSONException {
String jsonString = "[{\"file\":[{\"fileRefNo\":\"AG/CSD/1\",\"status\":\"Active\"}],\"requestNo\":\"225V49\"},{\"file\":[{\"fileRefNo\":\"AG/CSD/1\",\"status\":\"Inactive\"}],\"requestNo\":\"225SRV\"},{\"file\":[{\"fileRefNo\":\"AG/CSD/2\",\"status\":\"Active\"}],\"requestNo\":\"225SRV\"}]" ;
JSONArray json = new JSONArray(jsonString);
Map<String, Object> retMap = new HashMap<String, Object>();
for (int i = 0; i < json.length(); i++ ) {
if(json != JSONObject.NULL) {
retMap = toMap(json.getJSONObject(i));
System.out.println(retMap + "retMap");
//{file=[{fileRefNo=AG/CSD/1, status=Active}], requestNo=225V49}retMap
//{file=[{fileRefNo=AG/CSD/1, status=Inactive}], requestNo=225SRV}retMap
//{file=[{fileRefNo=AG/CSD/2, status=Active}], requestNo=225SRV}retMap
}
}
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while(keysItr.hasNext()) {
String key = keysItr.next();
Object value = object.get(key);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if(value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if(value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
这是我最初的JSONArray
[{
"file": [{
"fileRefNo": "AG/CSD/1",
"status": "Active"
}],
"requestNo": "225V49"
}, {
"file": [{
"fileRefNo": "AG/CSD/1",
"status": "Inactive"
}],
"requestNo": "225SRV"
}, {
"file": [{
"fileRefNo": "AG/CSD/2",
"status": "Active"
}],
"requestNo": "225SRV"
}]
这是我想要的结果
[{
"file": [{
"fileRefNo": "AG/CSD/1",
"status": "Active"
}],
"requestNo": "225V49"
}, {
"file": [{
"fileRefNo": "AG/CSD/1",
"status": "Inactive"
},{
"fileRefNo": "AG/CSD/2",
"status": "Active"
}],
"requestNo": "225SRV"
}]