我有一個非常複雜的json
結構。它包含很多array elements
,那些數組元素包含其他數組元素等等。 請看下面的json
樹形結構。如何檢索和更新json數組元素而不遍歷整個json
的Json樹結構-1:
的Json樹結構-2:
如黃色上面所強調的,我要更新的值「rdKey
」字段。 我寫了下面的代碼,它是完美的罰款工作:
String json = "escaped string (as it's a big string, I can't put it here)";
JSONObject jsonObj = new JSONObject(json);
if (jsonObj.has("responseMap")) {
JSONObject responseMap = jsonObj.getJSONObject("responseMap");
if (responseMap.has("ValueJson")) {
JSONObject valueJson = responseMap.getJSONObject("ValueJson");
if (valueJson.has("ticketBean_CM")) {
JSONObject ticketBean_CM = valueJson.getJSONObject("ticketBean_CM");
if (ticketBean_CM.has("addByGamma")) {
String addByGamma = ticketBean_CM.getString("addByGamma");
System.out.println(addByGamma);
if (addByGamma.equals("VCE")) {
if (responseMap.has("ScreenJson")) {
JSONObject screenJson = responseMap.getJSONObject("ScreenJson");
if (screenJson.has("sections")) {
JSONArray sectionArray1 = screenJson.getJSONArray("sections");
if (sectionArray1.length() > 0) {
JSONObject section0 = sectionArray1.getJSONObject(0);
if (section0.has("sections")) {
JSONArray sectionArray2 = section0.getJSONArray("sections");
if (sectionArray2.length() > 3) {
JSONObject section6 = sectionArray2.getJSONObject(3);
if (section6.has("sections")) {
JSONArray sectionArray3 = section6.getJSONArray("sections");
if (sectionArray3.length() > 1) {
JSONObject section8 = sectionArray3.getJSONObject(1);
if (section8.has("elements")) {
JSONArray elementsArray1 = section8
.getJSONArray("elements");
if (elementsArray1.length() > 0) {
JSONObject elements1 = elementsArray1.getJSONObject(0);
if (elements1.has("elements")) {
JSONArray elementsArray2 = elements1
.getJSONArray("elements");
if (elementsArray2.length() > 4) {
JSONObject elements2 = elementsArray2
.getJSONObject(4);
if (elements2.has("rdKey")) {
System.out.println(
elements2.getString("rdKey"));
elements2.put("rdKey",
"CircuitID(FullPartial)");
System.out.println(
elements2.getString("rdKey"));
System.out.println(jsonObj.toString());
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
我希望你們幫我,如果有這方面的任何更好的解決方案。我可以在沒有遍歷整個json
對象的情況下執行操作(直到找到相關字段)?如果json
樹結構發生變化,此解決方案將不起作用,它需要是靜態的,作爲此代碼的成功場景。
請建議更好的解決方案。
因爲你的編碼風格幾乎相同,所以你可以使用'for loop'作爲[「responseMap」,「ValueJson」,「ticketBean_CM」,...,4] –
我沒有通過它,請你幫忙。 – Punit
看起來你的結構中有很多條件(比如數組中的位置和一些列名)。它是一個特定的約束,就像你以後不需要類似的東西,或者你需要經常通過這些數組?對於後者,我建議創建表示您的對象的Java bean以便於訪問。否則,您可以創建自己的小API以避免重複「如果元素等等」。 – Asoub