简体   繁体   中英

Convert all JSON values into string

In java I have JSON in which all the values have to be changed to string. The values may be a number, boolean,null or anything.

{
    "obj1": [{
        "n1": "n",
        "n2": 1,
        "n3": true
    },
    {
        "n1": "n",
        "n2": 1,
        "n3": null
    }]
}

The expected result is all the values should be formatted as a string .

Example:

{
    "obj1": [{
        "n1": "n",
        "n2": "1",
        "n3": "true"
    },
    {
        "n1": "n",
        "n2": "1",
        "n3": "null"
    }]
}

By iterating through the JSON object we can do this, but is there any simpler way to do this, in which iteration works behind like using lambda function.

You can define a recursive function for this, say stringify , having three cases:

  • if it's a JSONObject , replace all the values with the stringified values
  • if it's a JSONArray , replace all the elements with the stringified elements
  • if it's anything else, return String.valueOf

Something like this:

public Object stringify(Object x) {
    if (x instanceof JSONObject) {
        JSONObject obj = (JSONObject) x;
        for (String key : obj.keySet()) {
            obj.put(key, stringify(obj.get(key)));
        }
    } else if (x instanceof JSONArray) {
        JSONArray arr = (JSONArray) x;
        for (int i = 0; i < arr.length(); i++) {
            arr.put(i, stringify(arr.get(i)));
        }
    } else {
        x = String.valueOf(x);
    }
    return x;
}

Example and application:

String s = "{\"obj1\": [{\"n1\": \"n\",\"n2\": 1,\"n3\": true},{\"n1\": \"n\",\"n2\": 1,\"n3\": null}]}";
JSONObject obj = new JSONObject(s);
obj = (JSONObject) stringify(obj);
// {"obj1":[{"n1":"n","n2":"1","n3":"true"},{"n1":"n","n2":"1","n3":"null"}]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM