如何解决如何使用@ JsonTypeInfo,@ JsonSubType根据同级字段的值确定字段类型?
说我有一个像这样的类结构:-
class ShapeRequest {
ShapeInfo shapeInfo;
Shape shape;
static class ShapeInfo {
String shapeName;
String shapeDimension;
}
static abstract class Shape {
}
static class Square extends Shape{
int area;
}
static class Circle extends Shape{
int area;
}
}
如何根据 shapeInfo.shapeName 字段值,将字段 shape 映射为Square或Circle类型来反序列化ShapeRequest?
例如,下面的JSON应该映射到具有Circle形状类型的ShapeRequest,因为shapeInfo.shapeName =“ circle”
{
"shapeInfo": {
"shapeName": "circle","shapeDimension": "2"
},"shape": {
"area": 10
}
}
解决方法
您可以在下面使用它:
public class JsonTypeExample {
// Main method to test our code.
public static void main(String args[]) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
// json to circle based on shapeName
String json = "{\"shapeName\":\"circle\",\"area\":10}";
Shape shape = objectMapper.readerFor(Shape.class).readValue(json);
System.out.println(shape.getClass());
System.out.println(objectMapper.writeValueAsString(shape));
// json to square based on shapeName
json = "{\"shapeName\":\"square\",\"area\":10}";
shape = objectMapper.readerFor(Shape.class).readValue(json);
System.out.println(shape.getClass());
System.out.println(objectMapper.writeValueAsString(shape));
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,include = JsonTypeInfo.As.PROPERTY,property = "shapeName")
@JsonSubTypes({
@JsonSubTypes.Type(value = Square.class,name = "square"),@JsonSubTypes.Type(value = Circle.class,name = "circle")
})
static class Shape {
Shape() {
}
}
@JsonTypeName("square")
static class Square extends Shape {
public int area;
Square(int area){
super();
this.area = area;
}
}
@JsonTypeName("circle")
static class Circle extends Shape {
public int area;
Circle(int area){
super();
this.area = area;
}
}
}
在这里Shape类用JsonTypeInfo和JsonSubTypes注释。
@JsonTypeInfo用于指示要包含在序列化和反序列化中的类型信息的详细信息。 这里 property 表示确定子类型时要考虑的值。
@JsonSubTypes用于指示带注释的类型的子类型。 在这里, name 和 value 将shapeName映射到适当的SubType类。
每当通过示例传递JSON时,反序列化都会通过JsonSubTypes进行,然后它会基于 shapeName 返回适当的JAVA对象。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。