简体   繁体   中英

Cannot unmarshal JSON-to-object with JAX-RS (CXF)

Using latest version of CXF and other dependencies, I'm trying to unit test web services which produces and consumes JSON. Test works when method argument is String, but fails when argument is custom object. Following is the sample resource:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("testPost")
public Employee getPostTest(Employee data) {
    return data;
}

Following is the excerpt of a test case

    List<Object> providers = new ArrayList<Object>();
    providers.add(new JacksonJaxbJsonProvider());
    WebClient client = WebClient.create(ENDPOINT_ADDRESS, providers);
    client.accept("application/json");
    client.type("application/json");
    client.path("users/testPost/");
    Employee e = new Employee();
    e.setName("Test");
    Response r = client.post(e);

Last line of the above code throws the following exception:

Dec 05, 2016 2:46:50 AM org.apache.cxf.jaxrs.utils.JAXRSUtils logMessageHandlerProblem SEVERE: No message body reader has been found for class com.finity.model.Employee, ContentType: application/json Dec 05, 2016 2:46:50 AM org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper toResponse WARNING: javax.ws.rs.WebApplicationException: HTTP 415 Unsupported Media Type at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromMessageBody(JAXRSUtils.java:1315) at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameter(JAXRSUtils.java:826) at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameters(JAXRSUtils.java:789)

Tried the read using JSONParser but no go:

    Employee e = new Employee();
    e.setName("Test");
    Response r = client.post(e);

    MappingJsonFactory factory = new MappingJsonFactory();
    JsonParser parser = factory.createJsonParser((InputStream)r.getEntity());

You need to configure the JSON provider. For example Jackson

 <jaxrs:providers>
   <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
  </jaxrs:providers>

or JacksonJaxbJsonProvider (when working with JAXB beans)

It is needed also to add the maven dependency if you do not have it. org.codehaus.jackson jackson-jaxrs 1.9.0

See CXF JSON support

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