java - Jackson:避免尾随逗号

标签 java json jackson

我正在尝试使用 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,其中包含嵌套的 ListsMaps 并编写:

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/

相关文章:

Java/ jackson : Deserialize JSON into class with HashMap

java - 如何在使用 Spring Batch ItemWriter 写入文件时关闭分隔符

c++ - 将一个 long double 存储在多个 double 变量中

c# - 将字符串转换为 LiteDB BsonDocument

ruby-on-rails - Rails,为什么 '.to_json' 正在转义 html 实体

java - 从 Java 对象生成正确的 JSON - Jackson

java - hibernate 将多列映射到 arraylist

java - 将对象添加到具有排除的数组

java - 我正在尝试使用 docx4j 将图像添加到新的 word 文档

java - 使用 Spring 3 和 Jackson 1.9 的简单请求中出现错误 406