java - How to have Jackson use a method to serialize a class to JSON? -
let's have 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 instance of myclass, following:
{"t":{"test":50}}
is there annotation can put in test class force jackson invoke tocustomstring() method whenever serializing test object?
i'd see 1 of following outputs when jackson serializes instance of myclass:
{"t":"50.50"}
{"t":{"test":"50.50"}}
if want produce
{"t":"50.50"} you can use @jsonvalue indicates
that results of annotated "getter" method (which means signature must of getters; non-void return type, no args) used single value serialize instance.
@jsonvalue public string tocustomstring() { return test + "." + test; } if want produce
{"t":{"test":"50.50"}} you can use 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;