如何使用@ 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对象。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...