0

I am trying to create or update a JSON with a new key:value nodes inside a JsonArray. So far I am able to add simple values using a map of nodes, but I am unable to add an array.

The goal is to create a JSON string with the following values:

{
    "curfew": [{
        "enabled": true,
        "lock_time": "00:00",
        "unlock_time": "00:10"
    },
    {
        "enabled": true,
        "lock_time": "00:20",
        "unlock_time": "00:30"
    }]
}

Starting from a new and empty JSON and later adding more values (such as the second "curfew" array).

Map<String, Object> values = ImmutableMap.of(
                                    "enabled", true,
                                    "lock_time", "00:00",
                                    "unlock_time", "00:10");
String emptyJson = "{}"; //empty json
DocumentContext doc = getDocument(emptyJson)
doc.set(JsonPath.compile("$.curfew"), values).jsonString();

So far I am getting this (NOT AN ARRAY)

{
    "curfew": {
        "enabled": true,
        "lock_time": "00:00",
        "unlock_time": "05:00"
    }
}

1 Answer 1

2

Create a List<Map<String, Object>> and then add your map in the list

List<Map<String, Object>> list = new ArrayList<>();
list.add(values);

And set the list in doc

doc.set(JsonPath.compile("$.curfew"), list).jsonString();
Sign up to request clarification or add additional context in comments.

1 Comment

I was so close to that solution, but for some reason failed. this totally works! thank you

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.