0

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

1

2 Answers 2

1

You can either deserialise to Map<String, Object> (where the object can be another similar map), reach in to the structure, make your change, the serialise to json, or...

json = json.replaceAll("(?s)(\"cars":.*?\"car1":").*?\"", "$1" + newValue + "\"");
Sign up to request clarification or add additional context in comments.

1 Comment

Can you please explain how do it through 'Map<String, Object> ' and return the modified object. I cannot use replace all due to key-path variations. I can do the Json iterations as per the length of the keys, But no idea how to do it through iteration
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.