如何使用 Jersey JSON POJO 支持? [英] How do I use the Jersey JSON POJO support?

查看:21
本文介绍了如何使用 Jersey JSON POJO 支持?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,我想在 JSON 中作为 RESTful 资源提供服务.我像这样打开了 Jersey 的 JSON POJO 支持(在 web.xml 中):

I have an object that I'd like to serve in JSON as a RESTful resource. I have Jersey's JSON POJO support turned on like so (in 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>  

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

But when I try to access the resource, I get this exception:

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
...

我要服务的类并不复杂,它所拥有的只是一些公共的 final 字段和一个设置所有这些字段的构造函数.这些字段都是字符串、原语、与此类似的类或其列表(我尝试使用普通列表而不是通用列表<T>s,但无济于事).有谁知道给了什么?谢谢!

The class that I'm trying to serve isn't complicated, all it's got are some public final fields and a constructor that sets all of them. The fields are all strings, primitives, classes similar to this one, or Lists thereof (I've tried using plain Lists instead of generic List<T>s, to no avail). Does anyone know what gives? Thanks!

Java EE 6

球衣 1.1.5

玻璃鱼 3.0.1

推荐答案

Jersey-json 有一个 JAXB 实现.您收到该异常的原因是因为您没有 Provider 已注册,或者更具体地说是一个 MessageBodyWriter.你需要在你的提供者中注册一个合适的上下文:

Jersey-json has a JAXB implementation. The reason you're getting that exception is because you don't have a Provider registered, or more specifically a MessageBodyWriter. You need to register a proper context within your provider:

@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 的包.

This looks up for an @XmlRegistry within the provided package name, which is a package that contains @XmlRootElement annotated POJOs.

@XmlRootElement
public class Person {

    private String firstName;

    //getters and setters, etc.
}

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

then create an ObjectFactory in the same package:

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

注册 @Provider 后,Jersey 应该会为您的资源中的编组提供便利:

With the @Provider registered, Jersey should facilitate the marshalling for you in your resource:

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

这篇关于如何使用 Jersey JSON POJO 支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆