如何让 Jackson 使用方法将 class 序列化为 JSON?
How to have Jackson use a method to serialize a class to JSON?
假设我有以下 classes:
public class MyClass {
private Test t;
public MyClass() {
t = new Test(50);
}
}
public class Test {
private int test;
public Test(int test) {
this.test = test;
}
public String toCustomString() {
return test + "." + test;
}
}
当 Jackson 序列化 MyClass
的实例时,它将如下所示:
{"t":{"test":50}}
我可以在 Test
class 中添加任何注释以强制 Jackson 在序列化 Test
对象时调用 toCustomString()
方法吗?
当 Jackson 序列化 MyClass
的实例时,我希望看到以下输出之一:
{"t":"50.50"}
{"t":{"test":"50.50"}}
您正在查找 @JsonProperty
注释。只需将其放入您的方法即可:
@JsonProperty("test")
public String toCustomString() {
return test + "." + test;
}
此外,Jackson 一直拒绝连载 MyClass
,因此为避免出现问题,您可以在 t
属性.
中添加一个简单的 getter
如果你想生产
{"t":"50.50"}
你可以用@JsonValue
表示
that results of the annotated "getter" method (which means signature
must be that of getters; non-void return type, no args) is to be used
as the single value to serialize for the instance.
@JsonValue
public String toCustomString() {
return test + "." + test;
}
如果你想生产
{"t":{"test":"50.50"}}
您可以使用自定义 JsonSerializer
。
class TestSerializer extends JsonSerializer<Integer> {
@Override
public void serialize(Integer value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeString(value + "." + value);
}
}
...
@JsonSerialize(using = TestSerializer.class)
private int test;
假设我有以下 classes:
public class MyClass {
private Test t;
public MyClass() {
t = new Test(50);
}
}
public class Test {
private int test;
public Test(int test) {
this.test = test;
}
public String toCustomString() {
return test + "." + test;
}
}
当 Jackson 序列化 MyClass
的实例时,它将如下所示:
{"t":{"test":50}}
我可以在 Test
class 中添加任何注释以强制 Jackson 在序列化 Test
对象时调用 toCustomString()
方法吗?
当 Jackson 序列化 MyClass
的实例时,我希望看到以下输出之一:
{"t":"50.50"}
{"t":{"test":"50.50"}}
您正在查找 @JsonProperty
注释。只需将其放入您的方法即可:
@JsonProperty("test")
public String toCustomString() {
return test + "." + test;
}
此外,Jackson 一直拒绝连载 MyClass
,因此为避免出现问题,您可以在 t
属性.
如果你想生产
{"t":"50.50"}
你可以用@JsonValue
表示
that results of the annotated "getter" method (which means signature must be that of getters; non-void return type, no args) is to be used as the single value to serialize for the instance.
@JsonValue
public String toCustomString() {
return test + "." + test;
}
如果你想生产
{"t":{"test":"50.50"}}
您可以使用自定义 JsonSerializer
。
class TestSerializer extends JsonSerializer<Integer> {
@Override
public void serialize(Integer value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeString(value + "." + value);
}
}
...
@JsonSerialize(using = TestSerializer.class)
private int test;