java – 如何使用Jersey JSON POJO支持?

我有一个对象,我想在JSON中作为一个RESTful资源。我有泽西的JSON POJO支持打开像这样(在web.xml):

<servlet>  
    <servlet-name>Jersey Web Application</servlet-name>  
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>  
</servlet>  

但是当我尝试访问资源,我得到这个异常:

SEVERE: A message body writer for Java type, class com.example.MyDto, and MIME media type, application/json, was not found
SEVERE: Mapped exception to response: 500 (Internal Server Error)
javax.ws.rs.WebApplicationException
...

我想要服务的类不复杂,它有一些公共最终字段和一个构造函数设置所有的。这些字段都是字符串,原语,与此类似的类,或其列表(我已经尝试使用纯列表而不是通用列表< T>,没有效果)。有人知道什么吗?谢谢!

Java EE 6

Jersey 1.1.5

GlassFish 3.0.1

最佳答案
Jersey-json有一个JAXB实现。你得到异常的原因是因为你没有注册Provider,或者更具体地说是一个MessageBodyWriter.你需要在你的提供者中注册一个适当的上下文:

@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
    private final static String ENTITY_PACKAGE = "package.goes.here";
    private final static JAXBContext context;
    static {
        try {
            context = new JAXBContextAdapter(new JSONJAXBContext(JSONConfiguration.mapped().rootUnwrapping(false).build(), ENTITY_PACKAGE));
        } catch (final JAXBException ex) {
            throw new IllegalStateException("Could not resolve JAXBContext.", ex);
        }
    }

    public JAXBContext getContext(final Class<?> type) {
        try {
            if (type.getPackage().getName().contains(ENTITY_PACKAGE)) {
                return context;
            }
        } catch (final Exception ex) {
            // trap, just return null
        }
        return null;
    }

    public static final class JAXBContextAdapter extends JAXBContext {
        private final JAXBContext context;

        public JAXBContextAdapter(final JAXBContext context) {
            this.context = context;
        }

        @Override
        public Marshaller createMarshaller() {
            Marshaller marshaller = null;
            try {
                marshaller = context.createMarshaller();
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            } catch (final PropertyException pe) {
                return marshaller;
            } catch (final JAXBException jbe) {
                return null;
            }
            return marshaller;
        }

        @Override
        public Unmarshaller createUnmarshaller() throws JAXBException {
            final Unmarshaller unmarshaller = context.createUnmarshaller();
            unmarshaller.setEventHandler(new DefaultValidationEventHandler());
            return unmarshaller;
        }

        @Override
        public Validator createValidator() throws JAXBException {
            return context.createValidator();
        }
    }
}

它在提供的包名称中查找一个@XmlRegistry,这是一个包含@XmlRootElement注释的POJO的包。

@XmlRootElement
public class Person {

    private String firstName;

    //getters and setters, etc.
}

然后在同一个包中创建一个ObjectFactory:

@XmlRegistry
public class ObjectFactory {
   public Person createNewPerson() {
      return new Person();
   }
}

注册@Provider后,Jersey应该方便您在资源中进行编组:

@GET
@Consumes(MediaType.APPLICATION_JSON)
public Response doWork(Person person) {
   // do work
   return Response.ok().build();
}

转载注明原文:java – 如何使用Jersey JSON POJO支持? - 代码日志