Introduction
I need to serialize a java object (Fahrweg
) that contains nested objects (all implement the interface FahrwegEreignis
) to json.
My code to do this is as follows:
Fahrweg fahrweg = new Fahrweg();
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(FahrwegEreignis.class, FahrwegEreignisMixIn.class);
ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
try {
String json = ow.writeValueAsString(fahrweg);
System.out.print(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
By default, the type of the object is not contained in the resulting json (I assume because JS is dynamically typed).
I would like to add a field to every object about like so: "type" : "classname"
.
I've read about the Jackson annotations, and I'm using mixin because I cannot modify the classes in question. My mixin interface (FahrwegEreignisMixIn
) looks like this:
import com.fasterxml.jackson.annotation.JsonProperty;
public interface FahrwegEreignisMixIn {
@JsonProperty("type")
//TODO
}
Question
What do I need to put at //TODO
?
My first instinct was Class<?> getClass();
but that doesn't work.
Answer
The answer in the duplicate question worked for me. I had to change
my FahrwegEreignisMixIn
to this:
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "type")
public interface FahrwegEreignisMixIn {}