我的需求是这样的
- 如果新字符串中的key在原字符串中存在,则更新原字符串的对应key的value。
- 如果新字符串中的key在原字符串中不存在,则将新字符串中的key和value添加到原字符串中。
- 如果原字符串中存在,新字符串中不存在的key,则不处理
话不多说 上代码
public class UpdateColumnJsonUtils {
public static void main(String[] args) {
String jsonString = "{\n" +
" \"scriptResult\": {\n" +
" \"loan_app_count\": 3,\n" +
" \"app_num_ratio_3\": 0.8,\n" +
" \"gender_data\": {\n" +
" \"a\":\"1\",\n" +
" \"c\":\"3\"\n" +
" }\n" +
" }\n" +
"}";
String newJsonString = "{\n" +
" \"scriptResult\": {\n" +
" \"loan_app_count\": 5,\n" +
" \"app_num_ratio_4\": 1,\n" +
" \"gender_data\": {\n" +
" \"a\":\"1\",\n" +
" \"b\":\"2\",\n" +
" \"d\":\"4\",\n" +
" \"e\":\"d5\"\n" +
" }\n" +
" }\n" +
"}";
System.out.println(getColumnJson(jsonString,newJsonString));
}
public static Map<String,Object> getColumnJson(String oldJsonString,String newJsonString) {
// 将原始的JSON字符串转换为JSONObject
JSONObject originalJsonObject = JSON.parseObject(oldJsonString);
JSONObject newJsonObject = JSON.parseObject(newJsonString);
// 更新原始JSON对象中的对应键值对
updateJsonObject(originalJsonObject, newJsonObject);
// 将更新后的JSONObject转换回JSON字符串
Map<String,Object> map = originalJsonObject.getInnerMap();
return map;
}
private static void updateJsonObject(JSONObject originalObject, JSONObject newObject) {
for (String key : newObject.keySet()) {
Object newValue = newObject.get(key);
Object oldValue = originalObject.get(key);
if (oldValue instanceof JSONObject && newValue instanceof JSONObject) {
// 如果新旧值都是JSONObject,则递归更新嵌套的JSON对象
updateJsonObject((JSONObject) oldValue, (JSONObject) newValue);
} else {
// 否则,直接更新对应键的值
originalObject.put(key, newValue);
}
}
}
}
结果:
{scriptResult={"loan_app_count":5,"gender_data":{"a":"1","b":"2","c":"3","d":"4","e":"d5"},"app_num_ratio_4":1,"app_num_ratio_3":0.8}}