Reputation: 356
I am attempting to iterate through a hash map and create a json string from the values. Im using the JSONSimple library to do so. I have the structure I want, but the values are being overwritten. The structure I am ending up with is
{
"new_id":{
"coordinates_list":{
"Coordinates: ":[
"lat: 27.0",
"lon: 28.0"
]
},
"t0vhf40cv86t":[
"123"
]
}
}
But there should be additional values in the JSON. Only the last row of the hash map is being included. Do I need to add another JSONObject that I write to?
JSONObject obj = new JSONObject(); // final json object written out
double lat = 20.00; // test data
double lon = 21.00; // test data
for (Map.Entry<String, List<String>> entry : data.entrySet()){
JSONObject childObj = new JSONObject();
JSONObject coordObj = new JSONObject();
JSONArray entities = new JSONArray();
JSONArray coordinates = new JSONArray();
String key = entry.getKey();
List<String> values = data.get(key);
for(String value : values){
entities.add(value);
}
childObj.put(key,entities);
// increments the test data
lat = lat +1;
lon = lon + 1;
coordinates.add("lat: " + lat);
coordinates.add("lon: " + lon);
coordObj.put("Coordinates: " ,coordinates);
childObj.put("coordinate list ", coordObj);
obj.put("new_id" , childObj);
}
Upvotes: 1
Views: 1891
Reputation: 141
You are always using "new_id" as the key on the "obj.put" line. For the first map entry, you set the value for that key on the JSON object. For each subsequent entry, you are replacing the value for that key, not adding a new key. That is why only the last entry in the map is represented in the JSON.
I'm not sure exactly what you're trying to accomplish, but you likely either need to use a different key each time through the loop or use a JSONArray instead of a JSONObject so that you don't need keys at all.
Upvotes: 2