我有一个Jackson可序列化对象,它包含了下面几层的其他对象。在某些情况下(可以用@JsonSerialize
注解),我想更改该内部对象的序列化。我似乎不知道如何做到这一点。
在下面的示例中,整个Foo
对象Request1
通过默认序列化进行序列化,但在Request2
中,Foo
的所有示例都使用自定义序列化程序进行序列化。
请求1 JSON:
{
id: "8c88e31c-f6da-4ce5-8c75-3cacd5cb6694",
pojo: {
foo: {
value1: "abc",
value2: "def"
},
bar: {
other: {
value1: "uvw",
value2: "xyz"
}
}
}
}
请求2 JSON:
{
id: "8c88e31c-f6da-4ce5-8c75-3cacd5cb6694",
pojo: {
foo: [
"abc",
"def"
],
bar: {
other: [
"uvw",
"xyz"
]
}
}
}
Request1.java:
public class Request1 {
private UUID id;
private MyPojo pojo;
}
型
Request2.java:
public class Request2 {
private UUID id;
@JsonSerialize(using = MyPojoSerializer.class)
private MyPojo pojo;
}
MyPojo.java:
public class MyPojo {
private Foo foo;
private Bar bar;
public static class Bar {
private Foo other;
}
}
Foo.java:
public class Foo {
private String value1;
private String value2;
用于MyPojo
的串行器:
public class MyPojoSerializer extends JsonSerializer<MyPojo> {
@Override
public void serialize(final MyPojo value, final JsonGenerator gen,
final SerializerProvider serializers) throws IOException {
// how to set custom serializer for Foo before serializing the MyPojo object???
gen.writeObject(value);
}
private static class FooSerializer extends JsonSerializer<Foo> {
@Override
public void serialize(final Foo value, final JsonGenerator gen,
final SerializerProvider serializers) throws IOException {
gen.writeStartArray();
gen.writeString(value.getValue1());
gen.writeString(value.getValue2());
gen.writeEndArray();
}
}
}
1条答案
按热度按时间wtzytmuj1#
我不确定是否有一种方法可以在序列化过程中实际注册自定义序列化程序,但是您可以使用以下代码轻松地完成您想要的任务:
它并不理想,因为您需要手动序列化每个字段(尽管
provider
使每个字段成为一行程序),但如果您陷入困境,它至少可以为您提供一条前进的道路。