gpt4 book ai didi

java - 如何在另一个自定义 JsonSerializer Jackson 中调用 JsonSerializer

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:08:33 24 4
gpt4 key购买 nike

我有两个类(class)。以二等领域第一。

class A {
@JsonSerializer(using = CustomBSerializer.class)
private B b;
}

class B {
...
}

我有两个自定义序列化程序:

class CustomBSerializer extends JsonSerializer<B> {
...
}

class CustomASerializer extends JsonSerializer<A> {
@Override
public void serialize(A a, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
jgen.writeStartObject();
//write here
jgen.writeEndObject();
}

}

我应该添加什么方法而不是在 CustomASerializer 中添加注释以使用 CustomBSerializer 写入字段 b 的序列化值?

最佳答案

您可以使用 writeObjectField方法。 Jackson 应使用默认或自定义序列化程序(如果存在)。

下面的例子:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.io.IOException;
import java.util.Date;

public class Main {

public static void main(String[] args) throws Exception {
B b = new B();
b.setProperty("Value");

A a = new A();
a.setB(b);

ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(a));
}
}

@JsonSerialize(using = ASerializer.class)
class A {

private B b;

public B getB() {
return b;
}

public void setB(B b) {
this.b = b;
}
}

class ASerializer extends JsonSerializer<A> {

@Override
public void serialize(A value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
gen.writeStartObject();
gen.writeStringField("now", new Date().toString());
gen.writeObjectField("b", value.getB());
gen.writeEndObject();
}
}

@JsonSerialize(using = BSerializer.class)
class B {

private String property;

public String getProperty() {
return property;
}

public void setProperty(String property) {
this.property = property;
}
}

class BSerializer extends JsonSerializer<B> {

@Override
public void serialize(B value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
gen.writeStartObject();
gen.writeStringField("p", value.getProperty());
gen.writeEndObject();
}
}

打印:

{
"now" : "Wed Aug 26 22:27:08 CEST 2015",
"b" : {
"p" : "Value"
}
}

关于java - 如何在另一个自定义 JsonSerializer Jackson 中调用 JsonSerializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32228680/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com