0

I have a map like following:

"key1": "value1",
"list[0].key1": "listkeyvalue1"
"list[0].key2": "listkeyvalue2"
"list[1].key1": "listkeyvalue1"
"list[1].key2": "listkeyvalue3"

Is there a framework which converts this key-value pairs into an json object/string for me, regarding the [x] instead of just flat? When currently using something like Jackson ObjectMapper I just get the flat output I know of ways doing it on my own, just searching for a more elegant way

new ObjectMapper().writeValueAsString(map);

leads to JSON String

{
"key1": "value1",
"list[0].key1": "listkeyvalue1"
"list[0].key2": "listkeyvalue2"
"list[1].key1": "listkeyvalue1"
"list[1].key2": "listkeyvalue3"
}

but I want the output to be:

{
    "key1": "value1",
    "list": [
        {
            "key1": "listkeyvalue1",
            "key2": "listkeyvalue2"
        },
        {
            "key1": "listkeyvalue1",
            "key2": "listkeyvalue3"        
        }
    ]
}

2 Answers 2

1

Library Josson function unflatten() with parameter '.[]' as the delimiter characters.

https://github.com/octomix/josson

Josson josson = Josson.fromJsonString(
    "{\"key1\": \"value1\"," +
    "\"list[0].key1\": \"listkeyvalue1\"," +
    "\"list[0].key2\": \"listkeyvalue2\"," +
    "\"list[1].key1\": \"listkeyvalue1\"," +
    "\"list[1].key2\": \"listkeyvalue3\"}");
JsonNode node = josson.getNode("unflatten('.[]')");
System.out.println(node.toPrettyString());

Output

{
  "key1" : "value1",
  "list" : [ {
    "key1" : "listkeyvalue1",
    "key2" : "listkeyvalue2"
  }, {
    "key1" : "listkeyvalue1",
    "key2" : "listkeyvalue3"
  } ]
}
Sign up to request clarification or add additional context in comments.

Comments

0

Among Jackson's configuration options is pretty-printing: https://github.com/FasterXML/jackson-databind#user-content-10-minute-tutorial-configuration

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.