@Test
void resolveJsonTest() throws Exception {
String source = "{\"k1\":\"v2\",\"k2\":{\"v2\":\"v2k1\"}}";
String target = "{\"k1\":{\"v1\":\"v1v1\"},\"k2\":{\"v2\":{\"v2k1\":\"v2v1\"}}}";
JSONObject jor = JSONObject.parseObject(source);
JSONObject jop = JSONObject.parseObject(target);
List<String> params = new ArrayList<>();
resolveJson(jor, jop, params);
System.out.println(params);
}
private void resolveJson(JSONObject jor, JSONObject jop, List<String> params) throws Exception {
Set<String> jorKeys = jor.keySet();
for (String k : jorKeys) {
Object jopNext;
Object jorNext;
if (jop.containsKey(k)) {
jopNext = jop.get(k);
jorNext = jor.get(k);
if (jorNext instanceof JSONObject) {
if (jopNext instanceof JSONObject) {
resolveJson((JSONObject) jorNext, (JSONObject) jopNext, params);
continue;
}
throw new Exception(jorNext + " 无法解析 " + jopNext);
} else {
if (jopNext instanceof JSONObject) {
if (((JSONObject) jopNext).containsKey(jorNext)) {
Object param = ((JSONObject) jopNext).get(jorNext);
if (param instanceof JSONObject) {
throw new Exception(jorNext + " 无法解析 " + param);
}
params.add((String) param);
continue;
} else {
throw new Exception(jopNext + " 不存在key " + jorNext);
}
}
}
} else {
throw new Exception(jop + " 不存在key " + k);
}
}
}
|