JavaRush /Java Blog /Random EN /Serialization in Jackson. How can I explicitly specify wh...
ColdDeath
Level 34
Москва

Serialization in Jackson. How can I explicitly specify which subclass to use?

Published in the Random EN group
Having read lectures at level 33, I can’t understand how, when serializing into JSON using Jackson, specify an additional field, type, for classes with the same fields, how to do this in lecture 4. I indicate that I want to enter the type field, but nothing happens Serialization in Jackson.  How can I explicitly specify which subclass to use?  - 1 . Please tell me what am I doing wrong? public class Solution { public static void main(String[] args) throws IOException { Cat cat = new Cat(); cat.name = "Murka"; cat.age = 5; cat.weight = 3; Dog dog = new Dog(); dog.name = "Killer"; dog.age = 8; dog.owner = "Bill Jefferson"; ArrayList pets = new ArrayList(); pets.add(cat); pets.add(dog); StringWriter writer = new StringWriter(); convertToJSON(writer, pets); System.out.println(writer.toString()); //[{"name":"Murka","age":5,"weight":3},{"name":"Killer","age":8,"owner":"Bill Jefferson"}] } public static void convertToJSON(StringWriter writer, Object object) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(writer, object); } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = Cat.class, name = "cat"), @JsonSubTypes.Type(value = Dog.class , name = "dog") }) public static class Cat extends Pet { public int age; public int weight; } public static class Dog extends Pet { public int age; public String owner; } public static class Pet { public String name; } }
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION