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

相关文章:
[url]http://wangxinchun.iteye.com/blog/2055677[/url]

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

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]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值