how to implement MessageBodyWriter method writeTo for json response?

不羁岁月 提交于 2020-01-07 06:44:26

问题


How should I configure writeTo method so that it convert detail to json response .

  @Override
public void writeTo(Detail detail, Class<?> type, Type genericType, Annotation[] annotation, MediaType mediaType,
        MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException 
{

     try {
            JAXBContext jaxbContext = JAXBContext.newInstance(detail.getClass());
            // serialize the entity myBean to the entity output stream
            jaxbContext.createMarshaller().marshal(detail, entityStream);


        } catch (JAXBException jaxbException) {
            jaxbException.printStackTrace();
            throw new ProcessingException(
                "Error serializing a "+ detail +" to the output stream", jaxbException);
        }

} 

Yet now I am getting XML response from it.

MY resource code is:

   @POST
@Produces({MediaType.APPLICATION_JSON})
@Path("testDetail")
public TestDetail testDetail()
{

    TestDetail testDetail = new TestDetail();
  return testDetail;
}

回答1:


Why are you writing your own MessageBodyWriter for JSON? Don't reinvent the wheel.

Use one JSON provider that integrates with Jersey and it will provide you a MessageBodyWriter implementation. At time of writing, Jersey integrates with the following modules to provide JSON support:

  • MOXy
  • Java API for JSON Processing (JSON-P)
  • Jackson
  • Jettison

Using Jackson as a JSON provider

See below the steps required to use Jackson as a JSON provider for Jersey 2.x:

Adding Jackson module dependencies

To use Jackson 2.x as your JSON provider you need to add jersey-media-json-jackson module to your pom.xml file:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.23.1</version>
</dependency>

To use Jackson 1.x it'll look like:

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson1</artifactId>
    <version>2.23.1</version>
</dependency>

Registering Jackson module

Besides adding the dependency mentioned above, you need to register JacksonFeature (or Jackson1Feature for Jackson 1.x) in your Application/ResourceConfig sub-class:

@ApplicationPath("/api")
public class MyApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<Class<?>>();
        classes.add(JacksonFeature.class);
        return classes;
    }
}
@ApplicationPath("/api")
public class MyApplication extends ResourceConfig {

    public MyApplication() {
        register(JacksonFeature.class);
    }
}

If you don't have an Application/ResourceConfig sub-class, you can register the JacksonFeature in your web.xml deployment descriptor. The specific resource, provider and feature fully-qualified class names can be provided in a comma-separated value of jersey.config.server.provider.classnames initialization parameter.

<init-param>
    <param-name>jersey.config.server.provider.classnames</param-name>
    <param-value>org.glassfish.jersey.jackson.JacksonFeature</param-value>
</init-param>

The MessageBodyWriter provided by Jackson is JacksonJsonProvider.


For more details, check the Jersey documentation about support for common media type representations.




回答2:


You shouldn't need to be writing your own serialization code. You are probably missing the jersey-media-json-jackson artifact dependency. Look through this example.



来源:https://stackoverflow.com/questions/38866516/how-to-implement-messagebodywriter-method-writeto-for-json-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!