Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Json from java Map

Tags:

java

json

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.

like image 305
user1619355 Avatar asked Mar 18 '26 10:03

user1619355


1 Answers

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.

like image 63
Troley Avatar answered Mar 20 '26 03:03

Troley