Unveränderliche / polymorphe POJO <-> JSON-Serialisierung mit Jackson

Ich versuche, mit Jackson 2.1.4 ein unveränderliches POJO von und zu JSON zu serialisieren, ohne einen benutzerdefinierten Serializer schreiben zu müssen und mit möglichst wenigen Anmerkungen. Ich möchte auch vermeiden, unnötige Getter oder Standardkonstruktoren hinzufügen zu müssen, um die Jackson-Bibliothek zufrieden zu stellen.

Ich stecke jetzt in der Ausnahme fest:

JsonMappingException: Es wurde kein geeigneter Konstruktor für den Typ [einfacher Typ, Klasse Circle] gefunden: Kann nicht vom JSON-Objekt instanziiert werden (Typinformationen müssen hinzugefügt / aktiviert werden?)

Der 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;
  }
}

Der Testcode:

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);

Jede Hilfe wird sehr geschätzt, danke!

Antworten auf die Frage(3)

Ihre Antwort auf die Frage