Created
September 19, 2016 07:41
-
-
Save xzer/fd854576dee3bf7a3f7e4695ec987ce0 to your computer and use it in GitHub Desktop.
Polymorphic mapping with jackson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.List; | |
import com.fasterxml.jackson.annotation.JsonSubTypes; | |
import com.fasterxml.jackson.annotation.JsonTypeInfo; | |
import com.fasterxml.jackson.annotation.JsonTypeName; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; | |
public class Zoo { | |
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") | |
@JsonSubTypes({ @JsonSubTypes.Type(value = Dog.class, name = "dog"), @JsonSubTypes.Type(value = Cat.class, name = "cat"), }) | |
public static abstract class Animal { | |
public Animal() { | |
} | |
public Animal(String name) { | |
this.name = name; | |
} | |
public String getName() { | |
return this.name; | |
} | |
public void setName(String s) { | |
this.name = s; | |
} | |
public Animal getParent() { | |
return this.parent; | |
} | |
public void setParent(Animal p) { | |
this.parent = p; | |
} | |
private String name; | |
private Animal parent; | |
} | |
@JsonTypeName("dog") | |
public static class Dog extends Animal { | |
public Dog() { | |
} | |
public Dog(String name) { | |
super(name); | |
} | |
} | |
@JsonTypeName("cat") | |
public static class Cat extends Animal { | |
public Cat() { | |
} | |
public Cat(String name) { | |
super(name); | |
} | |
} | |
public static void main(String... args) throws Exception { | |
Zoo zoo = createZoo(); | |
ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); | |
String json1 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(zoo); | |
System.out.println("+++>>>" + json1); | |
zoo = mapper.readValue(json1, Zoo.class); | |
String json2 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(zoo); | |
System.out.println("Equals: " + json1.equals(json2)); | |
} | |
private static Zoo createZoo() { | |
Zoo zoo = new Zoo(); | |
Dog dog1 = new Dog("Dog1"); | |
Dog dog2 = new Dog("Dog2"); | |
Cat cat1 = new Cat("Cat1"); | |
Cat cat2 = new Cat("Cat2"); | |
dog2.setParent(dog1); | |
cat2.setParent(cat1); | |
zoo.add(dog1); | |
zoo.add(dog2); | |
zoo.add(cat1); | |
zoo.add(cat2); | |
return zoo; | |
} | |
private List<Animal> animals = new ArrayList<>(); | |
public void add(Animal animal) { | |
animals.add(animal); | |
} | |
public void setAnimals(List<Animal> list) { | |
this.animals = list; | |
} | |
public List<Animal> getAnimals() { | |
return this.animals; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment