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"
}
}
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();