杰克逊序列化:包裹领域 [英] Jackson serialization: Wrap fields
问题描述
当我们打开嵌套对象并将其字段写入主对象时,有一个众所周知的情况,我需要做一个反向任务。
There is a good known case when we unwrap nested object and write its fields into the main object, and I need to make an inverse task.
我有一个POJO:
class A {
private String id = "id1";
@JsonWrap("properties")
private String property1 = "...";
@JsonWrap("properties")
private String property2 = "...";
// getters and setters
}
默认序列化器将按预期生产
Default serializer will produce as expected
{
"id": "id1",
"property1": "...",
"property2": "..."
}
但是,我的JSON应该符合某些规范,为此,我需要在 property1
和 property2
内包装属性
包装器。因此结果应如下所示:
But, my JSON should match some specification, and to do that, I need to wrap property1
and property2
inside properties
wrapper. So the result should looks like:
{
"id": "id1",
"properties":
{
"property1": "...",
"property2": "..."
}
}
我不想改变POJO的结构,所以我看到了3种可能的方式:
I don't want to change the structure of the POJO so I see 3 possible ways:
- 编写自定义序列化程序。但是在我看来,编写这样的序列化器需要花费更多精力然后手工序列化对象。
- 创建代理Java对象,它将反映JSON的正确结构,并序列化这样的代理。
- 生成后修改JSON。 (我担心重读和重写JSON会有很大的开销)。
有人制作这样的Serializer或者知道吗使用我需要的结构生成JSON的另一个选项?
Does anybody make such Serializer or maybe know another options to generate JSON with the structure I need?
对于自定义序列化程序
我想重用标准BeanSerializer,I不想手动写出所有字段:
For custom serializer
I want to reuse standard BeanSerializer, I dont want to write out all fields manually:
- 隐藏带注释的字段。
- 写出bean,没有带注释的字段,但不要关闭对象。 (不要调用
jgen.writeEndObject();
) - 写出包装好的字段。
- 关闭对象。
- Hide annotated fields.
- Write out bean, without annotated fields, but don't close object. (Don't call
jgen.writeEndObject();
) - Write out wrapped fields.
- Close object.
推荐答案
您需要更改模型。
@JsonSerialize(using = ASerializer.class)
class A {
private String id;
private String property1;
private String property2;
// getters and setters
public static class ASerializer extends JsonSerializer<A> {
@Override
public void serialize(A value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeStringField("id", value.getId());
jgen.writeObjectFieldStart("properties");
jgen.writeStringField("property1", value.getProperty1());
jgen.writeStringField("property2", value.getProperty2());
jgen.writeEndObject();
jgen.writeEndObject();
}
}
}
在主要运行:
A a = new A();
a.setId("id1");
a.setProperty1("...");
a.setProperty2("...");
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer();
String json = writer.writeValueAsString(a);
System.out.println(json);
输出:
{"id":"id1","properties":{"property1":"...","property2":"..."}}
这篇关于杰克逊序列化:包裹领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!