简体   繁体   中英

Jersey doesn't unmarshall Java generic type

I would like to have a service that answers to POST requests on /contact with the following payload:

{"records":[{"firstname":"John","lastname":"Doe"}]} 

Ideally, records should be a wrapper for all sorts of types: Contact, Order, etc. That's why I would like to use a generic type, but Jersey doesn't seem to be able to unmarshall it. Here's my code:

@Controller
@Path("/contact")
public class ContactResource {

@Autowired
private ContactService contactService;

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public List<Contact> saveContact(final Records<Contact> contact) {
    return Arrays.asList(contactService.saveContact(contact.records.get(0)));
}
}


@XmlRootElement
public class Records<T> {
    public List<T> records;
}

It seems that using a custom javax.ws.rs.ext.MessageBodyReader could solve my problem. Correct?

It looks like you are using natural JSON Encoding - to be able to process it, you should configure Jersey as described here .

In some @PostConstruct in one of your singleton beans used for configuration, include the following call:

JSONConfiguration.natural().build();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM