'Remove Map Node from JSON
I am creating a JSON in Java:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
String json = null;
Map<String, String> data1 = new HashMap<String, String>();
Map<String, String> data2 = new HashMap<String, String>();
data1.put("name", "f1");
data1.put("key", "aa1");
data1.put("value", "21");
data2.put("name", "f2");
data2.put("key", "aa1");
data2.put("value", "22");
JSONObject json1 = new JSONObject(data1);
JSONObject json2 = new JSONObject(data2);
JSONArray array = new JSONArray();
array.put(json1);
array.put(json2);
JSONObject finalObject = new JSONObject();
try {
finalObject.put("DeltaRealTime", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
json = new Gson().toJson(finalObject);
What I get is the following:
{
"map": {
"DeltaRealTime": {
"myArrayList": [{
"map": {
"name": "f1",
"value": "21",
"key": "aa1"
}
}, {
"map": {
"name": "f2",
"value": "22",
"key": "aa1"
}
}]
}
}
}
But I do not want to have all these extra "map" nodes. What I can I do to remove them? Or what I can I do that I do not have them in the first place?
Solution 1:[1]
I would suggest using an Object to JSON string converter lib like Jackson. You can get a json str in three simple steps and dont have to create any JSON objects:
Steps
- Create a POJO class
- Populate the POJO object
Convert the object to a JSON string using the method as how below:
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(FooPOJO);
Ref: http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
Solution 2:[2]
My answer may help anyone in the future as none of the answers above worked for me. I just called toMap() on the JSONObject and all occurences of the map key were gone.
Solution 3:[3]
you can try as:
String requestBody=data1.toString(); String requestBody=data2.toString();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Srikanta |
| Solution 2 | mikaelovi |
| Solution 3 | Shilendra Patel |
