Home > Mobile >  Flatten Java Map that contains nested Maps as well in single Map
Flatten Java Map that contains nested Maps as well in single Map

Time:05-10

I have a Java Map<String, Object> that results from Jackson's convertValue(CustomType, new TypeReference<Map<String, Object>>() { }).

CustomType have nested objects that can be complex as well — and these could contain others in the same way.

I'm trying to find a library to flatten that Java Map into something like this:

# This would be a Map<String, Object>
root_field1: value1
root_field2: value2
nested1.field1: value3
nested1.field2: value4
nested2.field1: value5
nested2.field2: value6
root_field3: value7

The problem I'm facing is that I would need to use JSONPath later to update some of these values in a persistence engine, so I prefer to have everything in a collection because it's easier to traverse than Maps.

I've tried to implement this using the Stream API, but it becomes messy really quick — same with recursion. I wonder if there is a library to accomplish this in an easy, straightforward fashion...because so far, I haven't find anything.

CodePudding user response:

You can use Json Map flattener (Spring Vault) :-

    final Map<String, Object> map = new HashMap<>(); // your original map
    Map<String, String> keyMap = JsonMapFlattener.flattenToStringMap(map);
    //Input

    {"key": {"nest": 1}, "key2": ["1", "2"] }

    //Output

    key.nest=1
    key2[0]="1"
    key2[1]="2"
  • Related