我遇到了一种情况,传入的json可能有一个对象或数组-同一个键的格式不一致。因此,在处理之前,我需要转换具有对象而不是数组的json。我基本上有一个jsonpath列表,需要检查和更新。
我尝试过不同的方法,下面的代码是最新的。delete部分按预期工作,但是add没有添加数组。我也试着用set和put代替add
private static void modifyInputJsonForArray(String originalInputJsonStr, Set<String> mismatchingArrayPaths) {
//mismatchingArrayPaths.add("$.PayLoad.NBHdr.AppCoverages.AppCoveragesPartyRole[0].Party.PartyAddress");
//Need to convert PartyAddress from JsonObject to JsonArray
JsonObject originalInputJsonObj = new Gson().fromJson(originalInputJsonStr, JsonObject.class);
System.out.println("original json " + prettyPrintJson(originalInputJsonObj));
for (String mismatchingArrayPath : mismatchingArrayPaths) {
JsonObject payload = JsonPath.using(config).parse(originalInputJsonStr).read(mismatchingArrayPath, JsonObject.class);
System.out.println("value at " + mismatchingArrayPath + " is " + prettyPrintJson(payload));
DocumentContext payloadRemoved = JsonPath.using(config).parse(originalInputJsonStr).delete(mismatchingArrayPath);
JsonObject val1 = payloadRemoved.read("$");
System.out.println("Json after deleting value at " + mismatchingArrayPath + " is " + prettyPrintJson(val1));
JsonArray payloadArray = jsonnObjectToJsonArray(payload);
System.out.println("payloadArray "+ payloadArray);
payloadRemoved.set(JsonPath.compile(mismatchingArrayPath), payloadArray);
JsonObject val2 = payloadRemoved.read("$");
System.out.println("payloadRemoved readded array value at " + mismatchingArrayPath + " is " + prettyPrintJson(val2));
}
}
有什么建议可以让这个工作吗?
谢谢您
暂无答案!
目前还没有任何答案,快来回答吧!