ashok
ashok

Reputation: 1268

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.

Upvotes: 0

Views: 1576

Answers (1)

tobias_k
tobias_k

Reputation: 82929

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"}]}

Upvotes: 2

Related Questions