Jackson objectmapper忽略嵌套的json

时间:2014-06-05 20:59:34

标签: json jackson

我正在使用Jackson将json转换为地图,但我希望objectmapper忽略嵌套的json,所以如果我有json之类的话:

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

我希望输出如下:

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

1 个答案:

答案 0 :(得分:2)

我不知道如何配置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"}]}