转载

json-jackson多子类继承的反序列化

相关文章:

http://wangxinchun.iteye.com/blog/2055677

本文是一个例子,说明有继承情况下,多个子类的反序列化问题,看看代码吧

import java.util.ArrayList; import java.util.List;  import org.codehaus.jackson.annotate.JsonSubTypes; import org.codehaus.jackson.annotate.JsonTypeInfo; import org.codehaus.jackson.map.ObjectMapper;  /**  *   * @author xinchun.wang     @email: 532002108@qq.com  * @createTime 2015-3-24 下午8:27:12  */ public class JacksonJsonTest {  public static void main(String[] args) throws Exception {   List<A> dataList = new ArrayList<A>();   dataList.add(new C("10", 5));   dataList.add(new B(8, 5));   D d = new D();   d.setList(dataList);   ObjectMapper mapper = new ObjectMapper();   String data = mapper.writeValueAsString(d);   System.out.println(data);   D result = mapper.readValue(data, D.class);    System.out.println(result.getList());  }   public static class D {   List<A> list;    public List<A> getList() {    return list;   }    public void setList(List<A> list) {    this.list = list;   }   }   @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "typeName")  @JsonSubTypes({ @JsonSubTypes.Type(value = B.class, name = "B"),    @JsonSubTypes.Type(value = C.class, name = "C") })  public static class A {   protected int a;    public A() {   }    public A(int a) {    this.a = a;   }    public int getA() {    return a;   }    public void setA(int a) {    this.a = a;   }   }   @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "typeName")  public static class B extends A {   public B() {   }    public B(int b, int a) {    super(a);   }    private int b;    public int getB() {    return b;   }    public void setB(int b) {    this.b = b;   }  }   @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "typeName")  public static class C extends A {   private String c;    public C() {   }    public C(String c, int a) {    super(a);    this.c = c;   }    public String getC() {    return c;   }    public void setC(String c) {    this.c = c;   }   } }

输出:

{"list":[{"typeName":"C","a":5,"c":"10"},{"typeName":"B","a":5,"b":0}]}

[JsonTest$C@7ed75415, JsonTest$B@6ad16fc1]

正文到此结束
Loading...