De-serializing JSON to polymorphic object model using Spring and JsonTypeInfo annotation

后端 未结 6 1365
[愿得一人]
[愿得一人] 2020-12-29 20:17

I have the following object model in my Spring MVC (v3.2.0.RELEASE) web application:

public class Order {
  private Payment payment;
}

@JsonTypeInfo(use = J         


        
6条回答
  •  清歌不尽
    2020-12-29 20:49

    The method registerSubtypes() works!

    @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type")
    public interface Geometry {
      //...
    }
    
    public class Point implements Geometry{
      //...
    }
    public class Polygon implements Geometry{
      //...
    }
    public class LineString implements Geometry{
      //...
    }
    
    GeoJson geojson= null;
    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.registerSubtypes(Polygon.class,LineString.class,Point.class);
    
    try {
        geojson=mapper.readValue(source, GeoJson.class);            
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    Note1: We use the Interface and the implementing classes. I fyou want jackson to de-serialize the classes as per their implementing classes, you have to register all of them using ObjectMapper's "registerSubtypes" method.

    Note2: In addition you use, " @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type")" as annotation with your Interface.

    You can also define the order of properties when mapper writes a value of your POJO as a json.

    This you can do using below annotation.

    @JsonPropertyOrder({"type","crs","version","features"})
    public class GeoJson {
    
        private String type="FeatureCollection";
        private List features;
        private String version="1.0.0";
        private CRS crs = new CRS();
        ........
    }
    

    Hope this helps!

提交回复
热议问题