我正在尝试使用 Jackson 2.1.4 将不可变的 POJO 与 JSON 进行序列化,而无需编写自定义序列化程序并使用尽可能少的注释。我还希望避免仅仅为了满足 Jackson 库而添加不必要的 getter 或默认构造函数。
我现在陷入了例外:
JsonMappingException:找不到类型 [简单类型,类 Circle] 的合适构造函数:无法从 JSON 对象实例化(需要添加/启用类型信息?)
代码:
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;
}
}
测试代码:
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);
非常感谢任何帮助,谢谢!
您可以(根据 API)用以下方式注释构造函数@JsonCreator http://fasterxml.github.com/jackson-annotations/javadoc/2.1.0/com/fasterxml/jackson/annotation/JsonCreator.html和参数@JsonProperty http://fasterxml.github.com/jackson-annotations/javadoc/2.1.0/com/fasterxml/jackson/annotation/JsonProperty.html.
public class Circle extends Shape {
public final int radius; // Immutable - no getter needed
@JsonCreator
public Circle(@JsonProperty("radius") 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
@JsonCreator
public Rectangle(@JsonProperty("w") int w, @JsonProperty("h") int h) {
this.w = w;
this.h = h;
}
}
编辑:也许你必须用注释 Shape 类@JsonSubTypes http://fasterxml.github.com/jackson-annotations/javadoc/2.1.0/com/fasterxml/jackson/annotation/JsonSubTypes.html从而可以确定Shape的具体子类。
@JsonSubTypes({@JsonSubTypes.Type(Circle.class), @JsonSubTypes.Type(Rectangle.class)})
public abstract class Shape {}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)