假设我有以下类(class):
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
类中放置任何注释以强制 Jackson 在序列化 Test
对象时调用 toCustomString()
方法?
当 Jackson 序列化 MyClass
的实例时,我希望看到以下输出之一:
{"t":"50.50"}
{"t":{"test":"50.50"}}
最佳答案
如果要生产
{"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;
关于java - 如何让 jackson 使用一种方法将类序列化为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29550006/