Search code examples
javarestserializationdeserializationjson-deserialization

Is there a way to send Map<String, CustomObject> via Rest service?


I have a server application where I have exposed some services. I am running this application on Grizzly Jersey server.

I also have a client application wherein I call the services exposed by server application. Again I am using the Jersey client to call the services.

Now I have a requirement wherein I want to return:

    Map<String, CustomObject>

from the rest service written in server application and I want other applications using my client to be able to retrieve the same map as is without going through any hassle.

Till now I have been passing CustomObject(s) from server application and my client deserializes the custom objects correctly. This works because I have registered JacksonJaxbJsonProvider instance with my Jersey Client.

I have already created a service which returns:

    Map<String, CustomObject>

But the problem here is at the receiving end I get:

    Map<String, Map<String, String>>

Basically while returning a Map from service my CustomObject gets serialized into JSON which can be visualised as:

    Map<String, String>

but at the receiving end it does not get deserialized back to CustomObject. Just to reiterate it works (deserializes) fine in cases where I return only CustomObject from service.

I know I can traverse in main Map and convert internal Map into CustomObject using ObjectMapper at client side but that is something I want to avoid as there might be thousands of CustomObjects available.

Can someone please help here?


Solution

  • You have to declare the type of the destination object when deserializing your json. For example:

    TypeReference<HashMap<String, CustomObject>> typeReference = new TypeReference<HashMap<String, CustomObject>>() {};
    Map<String, CustomObject> result = mapper.readValue(jsonInput, typeReference);