我有两个如下的JSON对象
firstJSON: {"200":"success"}
secondJSON: {"401":"not found"}
我需要使用Java将它们合并为{"codes":{"200":"success"},{"401":"not found"}}
。
我尝试了3种方法,但无法实现所需的输出。您能帮忙代码片段吗?
我尝试过的代码如下
JSONObject firstJSON = new JSONObject();
firstJSON.put("200", "success");
String firstJSONStr = firstJSON.toString();
System.out.println("firstJSONStr--> " + firstJSONStr);
JSONObject secondJSON = new JSONObject();
secondJSON.put("401", "not found");
String secondJSONStr = secondJSON.toString();
System.out.println("secondJSONStr--> "+secondJSONStr);
String finalJSONStr = firstJSONStr + "," + secondJSONStr;
JSONObject finalJSON1 = new JSONObject();
finalJSON1.put("codes", new JSONObject(finalJSONStr));
System.out.println("finalJSON1--> " + finalJSON1.toString());
JSONObject finalJSON2 = new JSONObject();
finalJSON2.put("codes", finalJSONStr);
System.out.println("finalJSON2--> " + finalJSON2.toString());
JSONObject finalJSON3 = new JSONObject();
ArrayList<JSONObject> jsonArray = new ArrayList<JSONObject>();
jsonArray.add(firstJSON);
jsonArray.add(secondJSON);
finalJSON3.put("codes", jsonArray);
System.out.println("finalJSON3--> " + finalJSON3.toString());
输出:
firstJSONStr--> {"200":"success"}
secondJSONStr--> {"401":"not found"}
finalJSON1--> {"codes":{"200":"success"}}
finalJSON2--> {"codes":"{\"200\":\"success\"},{\"401\":\"not found\"}"}
finalJSON3--> {"codes":[{"200":"success"},{"401":"not found"}]}
答案 0 :(得分:1)
您期望的JSON {"codes":{"200":"success"},{"401":"not found"}}
无效。您可以使用https://jsonlint.com/进行验证,这会产生错误:
Error: Parse error on line 4:
...00": "success" }, { "401": "not foun
---------------------^
Expecting 'STRING', got '{'
您最有可能希望将第一个和第二个对象归为一个数组,从而使结果低于JSON(请注意方括号[
和]
)
{"codes":[{"200":"success"},{"401":"not found"}]}
这可以通过以下方式实现:
JSONObject first = new JSONObject();
first.put("200", "success");
JSONObject second = new JSONObject();
second.put("401", "not found");
JSONArray codes = new JSONArray();
codes.put(first);
codes.put(second);
JSONObject root = new JSONObject();
root.put("codes", codes);
System.out.println(root);
答案 1 :(得分:0)
终于明白了逻辑。
JSONObject successJSON = new JSONObject();
successJSON.put("description", "success");
JSONObject scJSON = new JSONObject();
scJSON.put("200", successJSON);
JSONObject failJSON = new JSONObject();
failJSON.put("description","failure");
scJSON.put("401", failJSON);
JSONObject finalJSON = new JSONObject();
finalJSON.put("codes", scJSON);
System.out.println("finalJSON --> "+finalJSON.toString());