kok202
JsonTypeInfo, JsonSubTypes : 필드 값에 따라 파싱 타입 결정하기

2019. 10. 23. 15:50[개발] 기록

도형의 type 에따라 object 를 알맞은 타입으로 serialize, deserialize 한다.

@Data
@JsonTypeInfo(
    use= JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "type",
    visible = true)
@JsonSubTypes({
    @JsonSubTypes.Type(value = Rectangle.class, name = "rectangle"),
    @JsonSubTypes.Type(value = Circle.class, name = "circle"),
})
public abstract class Shape {
    private String type;
}

 

@Data
@NoArgsConstructor
public class Rectangle extends Shape {
    private int width;
    private int height;

    public Rectangle(String type, int width, int height) {
        setType(type);
        this.width = width;
        this.height = height;
    }
}

 

@Data
@NoArgsConstructor
public class Circle extends Shape {
    private int radius;

    public Circle(String type, int radius) {
        setType(type);
        this.radius = radius;
    }
}

 

public class MainTime {
    public static void main(String[] args) throws Exception{
        Map<String, Shape> map = new HashMap<>();
        map.put("shape1", new Rectangle("rectangle", 10, 20));
        map.put("shape2", new Circle("circle", 5));
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(map);
        System.out.println(json);
        Map<String, Shape> test = objectMapper.readValue(json, new TypeReference<Map<String, Shape>>(){});
        System.out.println(objectMapper.writeValueAsString(test));
    }
}

 

 

'[개발] 기록' 카테고리의 다른 글

카카오 페이 결제 흐름  (0) 2020.02.22
Parallel stream 과 Map  (0) 2020.01.07
Already had POJO for id 에러  (0) 2019.08.05
mvn vs mvnw  (0) 2019.06.26
자바 8 Stream  (0) 2019.06.06