我正在使用Jackson将json转换为地图,但我希望objectmapper
忽略嵌套的json,所以如果我有json之类的话:
{
"field1": "field1",
"fields": [{ "field2": "field2" }]
}
我希望输出如下:
{field1=field1, fields=[{ "field2": "field2" }]}
答案 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"}]}