Note that there are some explanatory texts on larger screens.

plurals
  1. POImmutable/polymorphic POJO <-> JSON serialization with Jackson
    primarykey
    data
    text
    <p>I'm trying to serialize a immutable POJO to and from JSON, using Jackson 2.1.4, without having to write a custom serializer and with as few annotations as possible. I also like to avoid having to add unnecessary getters or default constructors just to satisfy the Jackson library.</p> <p>I'm now stuck on the exception:</p> <p>JsonMappingException: No suitable constructor found for type [simple type, class Circle]: can not instantiate from JSON object (need to add/enable type information?)</p> <p>The code:</p> <pre><code>public abstract class Shape {} public class Circle extends Shape { public final int radius; // Immutable - no getter needed public Circle(int radius) { this.radius = radius; } } public class Rectangle extends Shape { public final int w; // Immutable - no getter needed public final int h; // Immutable - no getter needed public Rectangle(int w, int h) { this.w = w; this.h = h; } } </code></pre> <p>The test code:</p> <pre><code>ObjectMapper mapper = new ObjectMapper(); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); // Adds type info Shape circle = new Circle(10); Shape rectangle = new Rectangle(20, 30); String jsonCircle = mapper.writeValueAsString(circle); String jsonRectangle = mapper.writeValueAsString(rectangle); System.out.println(jsonCircle); // {"@class":"Circle","radius":123} System.out.println(jsonRectangle); // {"@class":"Rectangle","w":20,"h":30} // Throws: // JsonMappingException: No suitable constructor found. // Can not instantiate from JSON object (need to add/enable type information?) Shape newCircle = mapper.readValue(jsonCircle, Shape.class); Shape newRectangle = mapper.readValue(jsonRectangle, Shape.class); System.out.println("newCircle = " + newCircle); System.out.println("newRectangle = " + newRectangle); </code></pre> <p>Any help is greatly appreciated, thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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