I would like serialize an object such that one of the fields will be named differently based on the type of the field. For example:
public class Response {
private Status status;
private String error;
private Object data;
[ getters, setters ]
}
Here, I would like the field data to be serialized to something like data.getClass.getName() instead of always having a field called data which contains a different type depending on the situation.
How might I achieve such a trick using Jackson?
Using a custom
JsonSerializer.And then, suppose you want to serialize the following two objects:
The first one will print:
And the second one:
I have used the name
pfor the wrapper object since it will merely serve as aplaceholder. If you want to remove it, you’d have to write a custom serializer for the entire class, i.e., aJsonSerializer<Response>.