Reputation: 3497
I am using Jackson to convert json to a map, but I want the objectmapper
to ignore nested json, so if I have json like:
{
"field1": "field1",
"fields": [{ "field2": "field2" }]
}
I want the output like:
{field1=field1, fields=[{ "field2": "field2" }]}
Upvotes: 0
Views: 1188
Reputation: 10853
I don't see how you can configure ObjectMapper
to work as you wanted.
You possibly could consider making a two step conversion from the map of JsonNodes generated by the object mapper to the map which meets your requirements. Here is example:
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);
}
}
Output:
{fieldX=10.2, field1=field1, fields=[{"field2":"field2"}]}
Upvotes: 2