I have a JSON String like this in which I have key and value as shown below -
{
"u":{
"string":"1235"
},
"p":"2047935",
"client_id":{
"string":"5"
},
"origin":null,
"item_condition":null,
"country_id":{
"int":3
},
"timestamp":{
"long":1417823759555
},
"impression_id":{
"string":"2345HH*"
},
"is_consumerid":true,
"is_pid":false
}
As an example, one key is "u" and its value is -
{
"string":"1235"
}
Similarly another key is "country_id" and its value is -
{
"int":3
}
Similarly for others as well. Now what I need to do is, I need to represent the above key value as shown below. If any value is string data type, then represent it in double quotes, otherwise don't represent it in double quotes
"u": "1235"
"p": "2047935"
"client_id": "5"
"origin":null
"item_condition":null
"country_id": 3 // I don't have double quotes here around 3 since country_id was int that's why
"timestamp": 1417823759555
"impression_id": "2345HH*"
"is_consumerid": true
"is_pid": false
And then I need to make another json string which should look like this -
{
"u": "1235",
"p": "2047935",
"client_id": "5",
"origin":null,
"item_condition":null,
"country_id": 3,
"timestamp": 1417823759555,
"impression_id": "2345HH*",
"is_consumerid": true,
"is_pid": false
}
What is the best and efficient way to do this?
Update:-
This is what I have got -
JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
for (Map.Entry<String, JsonElement> object : jsonObject.entrySet()) {
if (object.getValue() instanceof JsonObject) {
String data = object.getValue().toString();
Map<String, Object> jsonIn = gson.fromJson(data, type);
Map<String, Object> jsonOut = new HashMap<String, Object>();
Set<String> keys = jsonIn.keySet();
for (String key : keys) {
Object value = jsonIn.get(key);
if (value instanceof Map) {
Map<?, ?> mapValue = (Map<?, ?>) value;
for (Map.Entry<?, ?> entry : mapValue.entrySet()) {
jsonOut.put(key, entry.getValue());
}
} else {
jsonOut.put(key, value);
}
}
// System.out.println(jsonOut);
Type typeOfMap = new TypeToken<Map<String, String>>() {
}.getType();
String json = gson.toJson(jsonOut, typeOfMap);
System.out.println(json);
}
}
Only thing which is not working is - when I try to serialize jsonOut map to a JSON, then all the values of a particular key gets converted to a string. But what I need is, only those values should get converted to a string (double quotes) which they are in general like country_id value should not be in double quotes since it is an integer as per my original JSON.