Skip to content
Advertisement

How to replace a value of the given key path in dynamic json object using java

I have dynamic JSONs and their key-path, I need to change the values of the Json on received key paths

As an example, in have below JSON and key (cars.car1)

{
   "name":"John",
   "age":null,
   "time":"2021",
   "vType":"yes",
   "cars":{
      "car1":"Ford",
      "car2":"BMW",
      "car3":"Fiat"
   },
   "lastOverScore":[
      4,
      1,
      6,
      6,
      2,
      1
   ],
   "letterSet":[
      "a",
      "b",
      "c",
      "d"
   ]
}

I need to change the value of cars.car1. as “Benz”. Also Please Note JSON body and its keys will change from time to time.

As an example, next time I may get a totally different JSON body with related key.

The key for the below JSON is: errors.source.pointer (Need to change the value of the given key)

{
  "errors": [
    {
      "source": { "pointer": "test" },
      "detail":  "Missing `data` Member at document's top level."
    }
  ]
}

Any idea to do this with Java

Advertisement

Answer

Through below code able to replace or remove the given item.

public JSONObject updateOrRemoveJsonProperty(Object js1, String keys, Object valueNew, ConfigData.JsonBuildType payloadEnum, String targetKey){
   try {
       List<String> keyMain = new LinkedList<String>(Arrays.asList(keys.split("\.")));

       for (int i = 0; i < keyMain.size(); i++) {
           if(js1 instanceof JSONObject || js1 instanceof JSONArray){
               if(keyMain.size() >1 && i+1 < keyMain.size()) {
                   String tmpKey= "";
                   String stringArray ="";
                   try {
                       tmpKey = keyMain.get(i);
                       keyMain.remove(i);
                       stringArray = StringUtils.join(keyMain, ".");
                       keyMain.clear();
                       updateOrRemoveJsonProperty(((JSONObject) js1).get(tmpKey), stringArray, valueNew, payloadEnum, targetKey);
                   }catch (JSONException js){
                       if(!tmpKey.isEmpty() && tmpKey.matches(KeyMapper.KEYLSTREGX)){
                           String[] tmp = tmpKey.replaceFirst(KeyMapper.KEYLSTREGX, "$1, $2").split(",");
                           try {
                               updateOrRemoveJsonProperty((JSONArray)(((JSONArray)((JSONObject) js1).get(tmp[0])).get(Integer.parseInt(tmp[1].trim()))), stringArray, valueNew, payloadEnum, targetKey);
                           }catch (ClassCastException ex){
                               updateOrRemoveJsonProperty((JSONObject)(((JSONArray)((JSONObject) js1).get(tmp[0])).get(Integer.parseInt(tmp[1].trim()))), stringArray, valueNew, payloadEnum, targetKey);
                           }
                       }
                   }
               } else {
                   if((keyMain.get(i)).length() > 2 && keyMain.get(i).matches(KeyMapper.KEYLSTREGX)){
                       String[] tmp = keyMain.get(i).replaceFirst(KeyMapper.KEYLSTREGX, "$1, $2").split(",");
                       if(targetKey != "" && tmp[0].trim().equals(targetKey) && !payloadEnum.equals(ConfigData.JsonBuildType.REMOVE)) {
                           ((JSONObject) js1).put(tmp[0], valueNew);
                       } else if (targetKey != "" && tmp[0].trim().equals(targetKey) && payloadEnum.equals(ConfigData.JsonBuildType.REMOVE)){
                           ((JSONObject) js1).remove(tmp[0]);
                       }

                   }
                   if(targetKey != "" && keyMain.get(i).equals(targetKey) && !payloadEnum.equals(ConfigData.JsonBuildType.REMOVE)) {
                       ((JSONObject) js1).put(keyMain.get(i), valueNew);
                   } else if (targetKey != "" && keyMain.get(i).equals(targetKey) && payloadEnum.equals(ConfigData.JsonBuildType.REMOVE)){
                       ((JSONObject) js1).remove(keyMain.get(i));
                   }
               }
           }
       }
   }catch (JSONException  ex){

   }

    return (JSONObject) js1;
}
Advertisement