杰克逊对象映射器忽略嵌套的JSON

汉克

我正在使用Jackson将json转换为地图,但是我想objectmapper忽略嵌套的json,所以如果我有json,例如:

{
   "field1": "field1",
   "fields": [{ "field2": "field2" }]
}

我想要这样的输出:

{field1=field1, fields=[{ "field2": "field2" }]}           
阿列克谢·加夫里洛夫(Alexey Gavrilov)

我看不到如何配置ObjectMapper即可按需工作。

您可能会考虑从对象映射器生成的JsonNodes映射到满足您要求的映射进行两步转换。这是示例:

public class JacksonIgnoreNestedMap {

    public static final String JSON = "{\n" +
            "   \"field1\": \"field1\",\n" +
            "   \"fields\": [{ \"field2\": \"field2\" }],\n" +
            "   \"fieldX\": 10.2\n" +
            "}";


    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, JsonNode> map = mapper.readValue(JSON, new TypeReference<Map<String, JsonNode>>() {});
        Map<String, Object> result = new HashMap<String, Object>();
        for (Map.Entry<String, JsonNode> e : map.entrySet()) {
            if (e.getValue().isContainerNode()) {
                result.put(e.getKey(), e.getValue().toString());
            } else {
                result.put(e.getKey(), mapper.convertValue(e.getValue(), Object.class));
            }
        }
        System.out.println(result);
    }
}

输出:

{fieldX=10.2, field1=field1, fields=[{"field2":"field2"}]}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章