Skip to content Skip to sidebar Skip to footer

Edit Json Fields

I have a JSON coming from server as below { 'XXXX': { 'type': 'RSS', 'value': '' }, 'YYYY': { 'type': 'String', 'value': '' },

Solution 1:

Try this

String jsonstring="{
    "XXXX": {
        "type": "RSS",
        "value": ""
    },
    "YYYY": {
        "type": "String",
        "value": ""
    },
    "ZZZZ": {
        "type": "String",
        "value": ""
    }
}";

JSONObject object=new JSONObject(jsonstring);
JSONObject childobject=object.getJSONObject("XXXX");

JSONObject modifiedjson=new JSONObject();
modifiedjson.put("type",childobject.get("type"));
modifiedjson.put("value","newvalue");  // Add new value of XXXX here//

JSONObject mmjson=new JSONObject();
mmjson.put("type","image");
mmjson.put("value","a7e8bec0-87ed-11e2-aa2e-52540025ab96_2_1362746556");  // Add new value of MMM here

JSONObject newjson=new JSONObject();
newjson.put("MMMM",mmjson.toString());
newjson.put("XXXX",modifiedjson.toString());
newjson.put("YYYY",object.get("YYYY"));
newjson.put("ZZZZ",object.get("ZZZZ"));

Solution 2:

I think you meant

{"XXXX":
{"type":"RSS","value":"},
"YYYY (mins)":{"type":"String","value":""},
"ZZZZ":{"type":"String","value":""}

is the JSON you get from server. You can always get the JSONObject.toString and edit it as required and then do something like,

JSONObject obj = newJSONObject(myString);

If you need to add a key value to JSON you may try,

JSONObject value = newJSONObject();
value.put("key","value");
value.put("key","value");//add all the field you want for ZZZZ.
obj.put("ZZZZ",value);

Solution 3:

If it is a string, you can just search for the specified values and concat the new string.

If it is a JSON Object, you could add new Values to the JSON Object and search for the values you want to manipulate and set them new.

What are you doing at the moment? Can you show us some code, so we know, where exactly you have the problem? And show, how you are accessing the JSON in this code, please.

Solution 4:

User Java String replacement method to replace string.

Take you Json as a string then replace value via string replacement method.

Here is small example.

String replaceSample = "This String replace Example shows how to replace one char from 

String newString = replaceSample.replace('r', 't');

Thanks.

Solution 5:

 var source={
                "XXXX": {
                    "type": "RSS",
                    "value": ""
                },
                "YYYY": {
                    "type": "String",
                    "value": ""
                },
                "ZZZZ": {
                    "type": "String",
                    "value": ""
                }
            }

And element you wanted to add

var element={
        "type": "Image",
        "value": "a7e8bec0-87ed-11e2-aa2e-52540025ab96_2_1362746556"
    };

You can do with below script,

source["MMMM"]=element;

or

source.MMMM=element;

Post a Comment for "Edit Json Fields"