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;
}
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: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 yourpom.xml
file:To use Jackson 1.x it'll look like:
Registering Jackson module
Besides adding the dependency mentioned above, you need to register
JacksonFeature
(orJackson1Feature
for Jackson 1.x) in yourApplication
/ResourceConfig
sub-class:If you don't have an
Application
/ResourceConfig
sub-class, you can register theJacksonFeature
in yourweb.xml
deployment descriptor. The specific resource, provider and feature fully-qualified class names can be provided in a comma-separated value ofjersey.config.server.provider.classnames
initialization parameter.The
MessageBodyWriter
provided by Jackson isJacksonJsonProvider
.For more details, check the Jersey documentation about support for common media type representations.
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.