[英]Changing POJO structure on returning to API call
I have assigned values to my POJO class to return as response body to an API call.我已经为我的 POJO 类分配了值,以作为 API 调用的响应主体返回。 I want to change my POJO structure, like by making the POJO as value to an object on top of the POJO.
我想更改我的 POJO 结构,例如将 POJO 作为 POJO 之上对象的值。
For example:例如:
Home POJO:首页 POJO:
{
int number;
String address;
}
Values are assigned to the POJO and I can send it as response body to my API call, but I want my response body to be:值已分配给 POJO,我可以将其作为响应主体发送到我的 API 调用,但我希望我的响应主体是:
{
output: {
number: 1,
address: "chennai"
}
}
I know that I can achieve this using JSON-Object or using a HashMap
or a parent POJO ( Note: I do not want to create a POJO Output
just for this case).我知道我可以使用 JSON-Object 或使用
HashMap
或父 POJO 来实现此目的(注意:我不想仅为这种情况创建 POJO Output
)。
Is there any other way to serialize the POJO like this using Jackson or any other methods for Java with Spring?有没有其他方法可以像这样使用 Jackson 或任何其他 Java 与 Spring 的方法来序列化 POJO?
You can apply @JsonRootName
annotation on your class specifying "output"
as its value.您可以在您的类上应用
@JsonRootName
注释,指定"output"
作为它的值。
@JsonRootName("output")
public class MyPojo {
private int number;
private String address;
// all-args constructor, getters, etc.
}
But this annotation alone would not have any impact on serialization.但是这个注释本身不会对序列化产生任何影响。 In order to make to instruct Jackson to use it, we need to enable the serialization feature
WRAP_ROOT_VALUE
:为了指示 Jackson 使用它,我们需要启用序列化功能
WRAP_ROOT_VALUE
:
Feature that can be enabled to make root value (usually JSON Object but can be any type) wrapped within a single property JSON object, where key as the "root name", ...
可以启用使根值(通常是 JSON 对象,但可以是任何类型)包装在单个属性 JSON 对象中的功能,其中键为“根名称”,...
Usage example:使用示例:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
System.out.println(
mapper
.writerWithDefaultPrettyPrinter()
.writeValueAsString(new MyPojo(1000, "foo"))
);
Output:输出:
{
"output" : {
"number" : 1000,
"address" : "foo"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.