0

Is there any library that provides converting HashMap into json string with nested objects based on doted values in map?

Java:

HashMap<String, String> params = new HashMap<>();
params.put("field_1", "value_1");
params.put("object_1.field_1", "value_1");
params.put("object_1.field_2", "value_2");
params.put("object_2.field_5", "value_5");
params.put("object_2.field_6", "value_6");

Should be converted to string:

{
    "field_1": "value_1",
    "object_1": {
        "field_1": "value_1",
        "field_2": "value_2"
    },
    "object_2": {
        "field_5": "value_5",
        "field_6": "value_6"
    }
}
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
Kamui
  • 13
  • 3
  • 1
    Did you try [this](https://stackoverflow.com/questions/12155800/how-to-convert-hashmap-to-json-object-in-java) – mnestorov Aug 28 '19 at 12:50
  • 3
    I don't think this feature exists on JSON libraries, but you can easily implement a function to transform your HashMap based on the doted keys to build a Map containing nested Map. – Dorian Aug 28 '19 at 12:50
  • I don't know if there is such library. But you can achieve that with a standard library like Jackson by implementing your serializer – cisk Aug 28 '19 at 12:51
  • 1
    The shortest way is to implement a custom serializer. See here, how to do it with Jackson: https://www.baeldung.com/jackson-custom-serialization – Eduard Dubilyer Aug 28 '19 at 12:53

1 Answers1

0

I have found library that can do it

    <dependency>
        <groupId>pl.jalokim.propertiestojson</groupId>
        <artifactId>java-properties-to-json</artifactId>
        <version>5.0.0</version>
    </dependency>

Simple as that:

new PropertiesToJsonConverter().convertToJson(params)
Kamui
  • 13
  • 3