I would like to generate a json formatted response from a Map.
I have tried the following for Map having String as the key and it works fine.
private JsonNode build(Map<String, List<PlaylistUrl>> entitiesPlaylist) {
JsonNode root = objectMapper.createObjectNode();
JsonNode data = objectMapper.createObjectNode();
((ObjectNode) data).set(ENTITIES, objectMapper.valueToTree(entitiesPlaylist));
((ObjectNode) root).set(DATA, data);
return root;
}
However I now have an object as a key instead of a String and would like to have all the values of the object printed as part of the response. I am not sure what logic to use here.
private JsonNode build(Map<Entity, List<PlaylistUrl>> entitiesPlaylist) {
JsonNode root = objectMapper.createObjectNode();
JsonNode data = objectMapper.createObjectNode();
for (Map.Entry<Entity, List<PlaylistUrl>> entry: entitiesPlaylist.entrySet()) {
// what logic ?
}
((ObjectNode) root).set(DATA, data);
return root;
}
I need the response to contain the Entity in the response as well as for each Entity the array list of Playlists.
Your build method could technically look something like this:
private JsonNode build(Map<Entity, List<PlayListUrl>> entitiesPlaylist) {
ArrayNode root = objectMapper.createArrayNode();
for (Map.Entry<Entity, List<PlayListUrl>> entry: entitiesPlaylist.entrySet()) {
JsonNode entityPlayListUrlsJsonObject = objectMapper.valueToTree(entry);
root.add(objectMapper.valueToTree(entityPlayListUrlsJsonObject));
}
return root;
}
In this case, each JsonNode added to the root ArrayNode will have the Entity#toString as the key. So overriding and customizing toString method of your Entity (sub)class(es) is a good idea, as else you will get the <package.to.TheClass@ObjectHexedHashCode> as key for each JSON object.
So, with an uncustomized toString method of the Entity, your JSON response will look something like:
[
{
"com.package.to.Entity@51931956": [
{
// First PlayListUrl object properties of this Entity
},
{
// Second PlayListUrl object properties of this Entity
},
...
]
},
{
"com.package.to.Entity@84569301": [
{
// First PlayListUrl object properties of this Entity
},
{
// Second PlayListUrl object properties of this Entity
}
...
]
},
...
]
I hope this helps you, or others if I'm late.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With