简体   繁体   English

在Jackson中重写JSON响应

[英]Overriding JSON Response in Jackson

I'd like to serialize, via Jackson, my Foo interface: 我想通过Jackson序列化我的Foo接口:

public interface Foo { }

It has two instances: Standard and Debug responses. 它有两个实例:标准和调试响应。 I'll only show the Standard response as it adequately conveys my question. 我只会显示Standard回答,因为它足以传达我的问题。

public class FooRegular implements Foo {

     private int number;

     public FooRegular(final int number) { this.number = number; }

     @JsonProperty("NUM")
     public getNumber() { 
       return number;
     }  
}

Note that, I'm returning a Foo in my Controller class: 请注意,我在Controller类中返回了Foo

public Response sendResponse() {
  Foo foo = getFoo(); // returns FooRegular
  return buildResponse(foo); // returns some Response with `foo` as its body
}

However, my response is: 但是,我的答复是:

{ number : 1234 }

I looked at this answer , which is what I've tried, but I'm not seeing the expected result. 我看着这个答案 ,这是我尝试过的,但是没有看到预期的结果。

How can I override the JSON response to have a key of NUM rather than number ? 如何覆盖JSON响应以使键为NUM而不是number

I tried your FooRegular class with an ObjectMapper and your JsonProperty annotation is working fine. 我用ObjectMapper尝试了FooRegular类,并且您的JsonProperty注释工作正常。 Without knowing what your buildResponse method looks like, I can only assume the problem is in there. 在不知道您的buildResponse方法是什么样的情况下,我只能假设问题出在那儿。

You could try one of these for your resource method: 您可以为您的资源方法尝试以下方法之一:

public Foo sendResponse() {
    return getFoo();
}

or 要么

public Response sendResponse() {
    Foo foo = getFoo();
    ObjectMapper mapper = new ObjectMapper();
    String foostr = mapper.writer().writeValueAsString(foo);
    return Response.ok().entity(foostr).build();
}

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

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