Reputation: 954
I'm trying to manually create a json representation using Jackson:
ObjectNode root = mapper.createObjectNode();
root.put("type", "FeatureCollection");
ArrayNode features = root.putArray("features");
for(M m : ms)
{
ObjectNode mEntry = mapper.createObjectNode();
mEntry.put("type", "Feature");
//properties
ObjectNode properties = mEntry.putObject("properties");
properties.put("id", m.getId());
//geometry
ObjectNode geometry = mEntry.putObject("geometry");
geometry.put("type", "Point");
//coordinates
ArrayNode coordinates = geometry.putArray("coordinates");
coordinates.add(m.getLongitude());
coordinates.add(m.getLatitude());
features.add(mEntry);
}
return mapper.writeValueAsString(root);
For some reason, this gives me a comma after the closing bracket of the coordinates array:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"id": 2006
},
"geometry": {
"type": "Point",
"coordinates": [
-1,
2
],
}
}
],
}
I get the same trailing in other places where I use ArrayNode in the generated JSON.
Any ideas on why this is happening and how I can avoid this comma?
Upvotes: 1
Views: 1247
Reputation: 425003
Don't bother dealing with the jackson API. Just create a regular Map
, with nested Lists
and Maps
and write that:
Map<String, Object> map = new HashMap<>();
map.put("type", "FeatureCollection");
List<Map<String, Object>> list = new ArrayList<>();
map.put("features", list);
Map<String, Object> map1 = new HashMap<>();
list.add(map1);
map1.put("type", "Feature");
Map<String, Object> map2 = new HashMap<>();
map1.put("properties", map2);
map2.put("id", 2006);
// etc
return mapper.writeValueAsString(map);
Upvotes: 2