作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我有两个类(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/
我是一名优秀的程序员,十分优秀!