How to get both JSON and XML response in Jersey having root element in both the cases?

安稳与你 提交于 2019-12-12 04:56:18

问题


I want response by using single function like:

@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getVolume(){
    ...enter code here
    return Response.ok().entity(VolDetail).build();
}

Output shoulb be like:

xml:
<volume>
   <status>available</status>
</volume>

JSON:
{"volume":{"status":"available"}}

where volume is a POJO class.

The problem is that I am not getting root element in JSON. I tried JSON object binding but its not working properly.


回答1:


Assuming you're using Jackson. You can configure the ObjectMapper to WRAP_ROOT_VALUE. You would do that in the ContextResolver. With Jackson 1.x, it would look like

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;

@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper>  {

    final ObjectMapper mapper = new ObjectMapper();

    public ObjectMapperContextResolver() {
        mapper.configure(Feature.WRAP_ROOT_VALUE, true);
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return mapper;
    }  
}

With Jackson 2.x, it would look like

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper>  {

    final ObjectMapper mapper = new ObjectMapper();

    public ObjectMapperContextResolver() {
        mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return mapper;
    }  
}

Your POJO should be annotated with @XmlRootElement(name = "volume") or @JsonRootName("volume")

If you don't want all your objects wrapped, you can configure different mappers for different classes, as seen here

Edit

With the above solution, only @JsonRootName will work. The reason is that by using our own ObjectMapper, we override the behavior of a JAXB annotation support configuration. We could explicitly add the support back by mapper.registerModule(new JaxbAnnotationModule());



来源:https://stackoverflow.com/questions/29473816/how-to-get-both-json-and-xml-response-in-jersey-having-root-element-in-both-the

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