java - How to modify the JSON data and return the updated JSON data -


we have requirement update json data in middle , need return updated json data using java. should support type of json data.

ex: assume {object:{"color":"red","shape":"triangle"}} json data , in need update shape value rectangle , need return updated json data below:

{object:{"color":"red","shape":"rectangle"}} 

for need pass element path ( element need update) , updatetext , json data java code.

here methodcall:

updatevalue("object/shape", "rectangle", "{object:{"color":"red","shape":"triangle"}}") 

we tried below code using gson library. code able update targeted json element, requirement return entire json data updated value.

so please suggest how re-build json data updated text.

below code tried update json data.

    public string updatevalue(string keypath, string updatetext, string jsontext) {     string[] keys = keypath.split("/");     jsonparser jsonparser = new jsonparser();     jsonobject jsonobject = (jsonobject) jsonparser.parse(jsontext);     string result = "";     for(string key : keys)     {         if (jsonobject.get(key) instanceof jsonobject)         {           jsonobject = (jsonobject)jsonobject.get(key);         }         else if(jsonobject.get(key) instanceof jsonarray)         {           jsonarray jsonarray = (jsonarray)jsonobject.get(key);           result = jsonarray.tostring();         }         else          {           result = jsonobject.get(key).tostring();         }                }     result = result.replace(result, updatetext);     return result;       } 

the problem lies in way replacements. when translate jsonobject string, lose object, , after replacement, have replaced string. fix it, need operate directly on object, instead of string counterpart. because jsonobject mutable, holding reference input reflect changes. 1 drawback can't replace value in jsonarray way, partly because don't know element replace. accomplish that, need little more in input(either value replace or element position).

public string updatevalue(string keypath, string updatetext, string jsontext) {     string[] keys = keypath.split("/");     jsonparser jsonparser = new jsonparser();     jsonobject jsonobject = (jsonobject) jsonparser.parse(jsontext);     jsonobject returnval = jsonobject; // holds ref target json object     jsonprimitive jp = new jsonprimitive(updatetext);     string finalkey = keys[keys.length - 1];     for(string key : keys)     {         if (jsonobject.get(key).isjsonobject())         {             jsonobject = (jsonobject)jsonobject.get(key);         }     }     jsonobject.remove(finalkey);     jsonobject.add(finalkey, jp);     return returnval.tostring();       } 

Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -