当 Java 对象中包含 数组集合对象时,将 JSON 字符串转成此对象。
public class Cart{}
public class MemberCoupon{}
public class CartGroup {
private List<Cart> carts = new ArrayList<Cart>(); // 购物车列表
private List<MemberCoupon> coupons = new ArrayList<MemberCoupon>(); // 优惠券列表
public List<Cart> getCarts() {
return carts;
}
public void setCarts(List<Cart> carts) {
this.carts = carts;
}
public List<MemberCoupon> getCoupons() {
return coupons;
}
public void setCoupons(List<MemberCoupon> coupons) {
this.coupons = coupons;
}
}
String jsonString = "{‘carts‘:[], ‘coupons‘:[]}";
Map<String, Class> classMap = new HashMap<String, Class>();
classMap.put("carts", Cart.class);
classMap.put("coupons", MemberCoupon.class);
JSONObject json = JSONObject.fromObject(jsonString);
CartGroup cGroup = (CartGroup)JSONObject.fromObject(json, CartGroup.class, classMap);
就可以的到一个完整的带有数组属性的CartGroup 对象了。
从而避免了net.sf.ezmorph.bean.MorphDynaBean cannot be cast to org.java.json.Cart 异常。