[英]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.