简体   繁体   English

使用ContainerResponseFilter中的Moxy进行JSON编组

[英]JSON unmarshalling with Moxy in ContainerResponseFilter

I'm using Moxy in my Jersey (2.7) project basically just to marshall my objects to JSON when the service issues a response. 我在我的Jersey(2.7)项目中使用Moxy基本上是为了在服务发出响应时将我的对象编组为JSON。 It works fine, but now I am also using ContainerResponseFilter to make some changes on every response issued and I am not sure how to unmarshall the content of the request body into an object, which is something I need. 它工作正常,但是现在我也使用ContainerResponseFilter对发出的每个响应进行一些更改,而且我不确定如何将请求主体的内容编组为对象,这是我所需要的。

Specifically: 特别:

  • i've just registered Moxy in a ResourceConfig instance: register(MOXyJsonProvider.class) 我刚刚在ResourceConfig实例中注册了Moxy: register(MOXyJsonProvider.class)
  • a class is using JAXB annotations, so when I set an instance of the class in Response.entity() it gets transformed into JSON properly 一个类正在使用JAXB批注,因此当我在Response.entity()中设置该类的实例时,它会正确地转换为JSON
  • the request body (also JSON) also gets unmarshalled into an object when I set it as a method paramether, for instance: 当我将请求主体(也称为JSON)设置为方法的方法时,它也会被解组到一个对象中,例如:

    @Consumes(MediaType.APPLICATION_JSON) public Response getSomething( MyClass instance ) {

However inside a ContainerResponseFilter I can access the request body like so, 但是在ContainerResponseFilter内部,我可以像这样访问请求正文,

InputStream body = requestContext.getEntityStream()

but I'm not sure if it's possible to have this also automatically converted into an object. 但我不确定是否可以将其也自动转换为对象。 The information I need is relatively simple, so I guess I could parse JSON in another way, but I'm curious. 我需要的信息相对简单,所以我想我可以用另一种方式解析JSON,但我很好奇。

I've tried searching, but I didn't find it. 我尝试搜索,但是没有找到。

In your ContainerReponseFilter, you can do something like this: 在您的ContainerReponseFilter中,您可以执行以下操作:

public class ApplicationResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(final ContainerRequestContext request,
        final ContainerResponseContext response) throws IOException {

        // your code
        response.getEntity();

    }
}

which converts it to your object with JAXB annotations. 使用JAXB注释将其转换为您的对象。 I was not doing it in my responseFilter, but I've just debugged it and it works. 我没有在responseFilter中执行此操作,但是我刚刚对其进行了调试,并且可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM