Let's say I have the following 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;
}
}
When Jackson serializes an instance of MyClass
, it will look like the following:
{"t":{"test":50}}
Is there any annotation I can put in the Test
class to force Jackson to invoke the toCustomString()
method whenever serializing a Test
object?
I'd like to see one of the following outputs when Jackson serializes an instance of MyClass
:
{"t":"50.50"}
{"t":{"test":"50.50"}}
If you want to produce
{"t":"50.50"}
you can use @JsonValue
which indicates
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;
}
If you want to produce
{"t":{"test":"50.50"}}
you can use a custom 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;
You are looking for @JsonProperty
annotation. Just put it to your method:
@JsonProperty("test")
public String toCustomString() {
return test + "." + test;
}
Also, Jackson consistently denied to serialize MyClass
, so to avoid problems you can add a simple getter to t
property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With