0

I am trying to auto serialize the below class as a parameter object via GSON, but my vocabularyCategoryMap always gets set to null

import lombok.Data;

import java.util.List;
import java.util.Map;

@Data
public class SearchRequestParameters {
    private int queryOffset;
    private String query;
    private Map<String, List<String>> vocabularyCategoryMap;
    private boolean sortByDate;
}

Here is the read from method from my GSON provider for JAX-RS

@Override
public Object readFrom(final Class<Object> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType,
        final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException, WebApplicationException {

    try (InputStreamReader streamReader = new InputStreamReader(entityStream, UTF_8)) {
        return getGson().fromJson(streamReader, type);
    }
}

This read from method has worked fine for me across a multitude of request parameter objects so far, but none of them have had a collection nested within a map. All of the examples for dealing with the situation (from googling) have suggested using specific type tokens, but that would break the generic nature of the existing gson provider. What is the best practices way for serializing nested json objects with GSON when using JAX-RS so that multiple GSON providers are not required?

Zak Thompson
  • 63
  • 2
  • 5
  • https://stackoverflow.com/questions/2779251/how-can-i-convert-json-to-a-hashmap-using-gson did you tried this – Gowrav Jan 09 '18 at 22:04
  • I had begun to go down a custom deserializer route (since I wanted the function to remain as generic as possible) but discovered there was a bug in my JSON – Zak Thompson Jan 09 '18 at 22:19

1 Answers1

0

Could you provide the json? This should work. A useful way to debug errors like this is to create your object and have gson output the json string. Compare this output string to your json to ensure that your class/json match. I test using the json below and did not receive a null vocabularyCategoryMap field.

{ "queryOffset":123, 
  "query":"select * from sometjhing", 
  "vocabularyCategoryMap":{ 
    "map1":[ "hiii", "byeee", "hiagain" ], 
    "map2":[ "hiii22222", "byeee2222", "hiagain2222" ] 
  }, 
  "sortByDate":true 
}
RobOhRob
  • 585
  • 7
  • 17
  • I was just able to confirm that it does work as intended. I had began to implement a custom gson deserializer to try to resolve the issue, but noticed that I was getting incorrect arguments in the JSON. Turns out there was an issue with my webpack on the front end, and the correct JSON was not getting sent to the backend. I messed around with webpack, and once the front end deployed properly, it started working as intended. – Zak Thompson Jan 09 '18 at 22:11