users@jersey.java.net

[Jersey] Question about JSON marshaling of response with nested generics

From: Noah White <emailnbw_at_gmail.com>
Date: Thu, 30 May 2013 17:26:51 -0400

Hi folks,

I'm having trouble attempting to marshal JSON from a class containing nested generics. Here's a ginned up example where I have a DTO with a property which contains a List of HashMaps:

MyDTO:

@XmlRootElement
public class MyDTO {

  private long id;
  private List<HashMap<String, String>> myDataMapList;

}

Resource class:

@Path("/dtos")
@RequestScoped
public class DTOResource {

  @Path("/{id}"}
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public Response getDTO(@PathParam("id") final long id) {
    ....
    MyDTO dto = new DTO();
    dto.setId(id);
    List<HashMap<String, String> dataMapList = new ArrayList<>();
    HashMap<String, String> hm1 = new HashMap<>();
    hm1.put("foo", "bar");
    HashMap<String, String> hm2 = new HashMap<>();
    hm2.put("baz", "bam");
    dataMapList.add(hm1);
    dataMapList.add(hm2);
    dto.setMyDataMapList(dataMapList);
    return Response.ok(dto).build();
  }

My JAXBContext resolver configures things such that this class will be part of a context that uses Natural notation and has root unwrap set to true like so:

return new JSONJAXBContext(JSONConfiguration.natural().rootUnwrapping(true).build(), MyDTO.class);

The JSON response ends up looking like so:

{"id":1,"myDataMapList":[null, null]}

On a hunch I tried the following changes to myDataMapList:

    private GenericEntity<List<HashMap<String, String>>> myDataMapList;

and
  
   private GenericEntity<List<GenericEntity<HashMap<String, String>>>> myDataMapList;
   

which both resulted in {"id":1,"myDataMapList":null}

Clearly I'm missing something here. Appreciate any pointers in the right direction. Thanks,

-Noah