Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing Jackson ObjectMapper to serialize the subclass name into JSON, not the superclass
    text
    copied!<p>In the following Jackson/Java code that serializes objects into JSON, I am getting this:</p> <pre><code>{"animal":{"x":"x"}} </code></pre> <p>However, what I actually want to get is this:</p> <pre><code>{"dog":{"x":"x"}} </code></pre> <p>Is there something I can do to AnimalContainer so that I get the runtime type ("dog", "cat") of the object, instead of "animal")? <strong>(<em>Edit:</em> I am aware that the map name comes from the getter- and setter- method names.)</strong> The only way I can think of to do it is within AnimalContainer to have an attribute of each type of Animal, have setters and getters for all of them, and enforce that only one is valued at a time. But this defeats the purpose of having the Animal superclass and just seems wrong. And in my real code I actually have a dozen subclasses, not just "dog" and "cat". Is there a better way to do this (perhaps using annotations somehow)? I need a solution for deserializing, as well.</p> <pre><code>public class Test { public static void main(String[] args) throws Exception { AnimalContainer animalContainer = new AnimalContainer(); animalContainer.setAnimal(new Dog()); StringWriter sw = new StringWriter(); // serialize ObjectMapper mapper = new ObjectMapper(); MappingJsonFactory jsonFactory = new MappingJsonFactory(); JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(sw); mapper.writeValue(jsonGenerator, animalContainer); sw.close(); System.out.println(sw.getBuffer().toString()); } public static class AnimalContainer { private Animal animal; public Animal getAnimal() {return animal;} public void setAnimal(Animal animal) {this.animal = animal;} } public abstract static class Animal { String x = "x"; public String getX() {return x;} } public static class Dog extends Animal {} public static class Cat extends Animal {} } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload