我正在尝试使用 Jackson 手动创建 json 表示:
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);
由于某种原因,这在坐标数组的右括号后面给出了一个逗号:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"id": 2006
},
"geometry": {
"type": "Point",
"coordinates": [
-1,
2
],
}
}
],
}
在生成的 JSON 中使用 ArrayNode 的其他地方,我得到了相同的尾随。
关于为什么会发生这种情况以及如何避免这个逗号有什么想法吗?
最佳答案
不用费心处理 Jackson API。只需创建一个常规的 Map
,其中包含嵌套的 Lists
和 Maps
并编写:
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);
关于java - Jackson:避免尾随逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48829079/