如何在java.util.ArrayList上添加JsonTypeInfo(注释)

时间:2014-02-27 08:08:08

标签: object serialization jersey jackson

我的POJO:

public class Album{

    private String title;  
    private Object tracks; // I can not change the type, beyond my control.. 

    /** setter **/
    ....
    /** getter **/
    ....
}

public class Track{

    private String title;  
    private String singer;  

    /** setter **/
    ....
    /** getter **/
    ....
}

主要方法:

public static void main(String[] args)
{
    Album album = new Album ();
    album.setTitle("Thriller");
    Track track = new Track();
    track.setTitle("Beat It");
    track.setSinger("M.J");
    List<Track> trackLst = new ArrayList<Track>();
    trackLst.add(track);
    Album.setTracks(trackLst);

    ObjectMapper mapper = new ObjectMapper();
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT, As.PROPERTY);
    m.writeValue(System.out, album);
}
    /** console printed **/
    {
        "title": "Thriller";
        "tracks":[
            "java.util.ArrayList",
            [
                {
                    "@class":"com.hs.Track",
                    "title":"Beat It",
                    "singer":"M.J"
                }
            ]
        ]
    }        

如您所见,轨道序列化为jsonArray,一个元素是类型(ArrayList),另一个元素是真正的jsonArray。有没有解决方案只保留真正的jsonArray?像这样:

{
        "title": "Thriller";
        "tracks":
            [
                {
                    "@class":"com.hs.Track",
                    "title":"Beat It",
                    "singer":"M.J"
                }
            ]
}

1 个答案:

答案 0 :(得分:0)

问题是类型声明private Object tracks,它导致属性匹配定义并强制使用列表的类型信息。如果它被声明为List<?>,则不会发生这种情况。

您可以做的一件事是使用“混合注释”来关联注释,如:

public class MixIn {
  @JsonDeserialize(as=List.class)
  @JsonSerialize(as=List.class)
  private Object tracks;
}

并注册混合以应用于课程Album。这应表明预期类型为List,并避免包含类型信息