简体   繁体   中英

Jackson: avoid trailing comma

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM