资源说明:因为JDK1.3/1.4不支持泛型,所以写法比支持对象嵌套的要复杂,附件是自己研究的一个例子
/* ===========================JSON字符串转换为Java Object===============================*/
String sibill = "";
sibill = "{\"blno\":\"123\",\"cutofftime\":\"2011-1-12\",\"vsl\":\"vsl\",\"voy\":\"voy\",\"port\":\"port\",\"consigneename\":\"consigneename\",\"consigneeaddress\":\"consigneeaddress\",\"consigneecityc\":\"consigneecitycountry\","+
"\"cntr\":[{\"cntrno\":\"111111\",\"cl\":\"拼箱\",\"sealnum\":\"sealnum1\",\"size\":\"40\",\"box\":\"H1\",\"cgo\":[{\"cgonum\":\"cgonum11\",\"cgoweight\":\"cgoweight1\",\"cgosize\":\"cgosize1\",\"cgohscode\":\"cgohscode1\",\"cgoowner\":\"cgoowner1\"}]},"+
"{\"cntrno\":\"222222\",\"cl\":\"整箱\",\"sealnum\":\"sealnum2\",\"size\":\"48\",\"box\":\"G1\",\"cgo\":[{\"cgonum\":\"cgonum21\",\"cgoweight\":\"cgoweight1\",\"cgosize\":\"cgosize1\",\"cgohscode\":\"cgohscode1\",\"cgoowner\":\"cgoowner1\"},{\"cgonum\":\"cgonum22\",\"cgoweight\":\"cgoweight2\",\"cgosize\":\"cgosize2\",\"cgohscode\":\"cgohscode2\",\"cgoowner\":\"cgoowner2\"}]}]"+
"}";
/* 第一步 (直接转换为Java Object) */
SiBillBean sibillbean = (SiBillBean)JSONObject.toBean(JSONObject.fromObject(sibill),SiBillBean.class);
/* 第二布 (取出嵌套对象属性值) */
JSONArray arrCntr = sibillbean.getCntr();
for (int i = 0; i < arrCntr.size(); i++) {
JSONObject cntr = (JSONObject)arrCntr.get(i);
CntrBean cntrBean = (CntrBean)JSONObject.toBean(cntr,CntrBean.class);
System.out.println(cntrBean);
JSONArray arrCgo = cntrBean.getCgo();
for (int j = 0; j < arrCgo.size(); j++) {
JSONObject cgo = (JSONObject)arrCgo.get(j);
CgoBean cgoBean = (CgoBean)JSONObject.toBean(cgo,CgoBean.class);
System.out.println(cgoBean);
}
}
/* 第二布 end */
/* ===========================Java Object转换为JSON字符串===============================*/
//CGO 1/2/3
CgoBean cgoBean1 = new CgoBean();
cgoBean1.setCgonum("cgo11");
CgoBean cgoBean2 = new CgoBean();
cgoBean2.setCgonum("cgo21");
CgoBean cgoBean3 = new CgoBean();
cgoBean3.setCgonum("cgo22");
//CNTR1
CntrBean cntrBean1 = new CntrBean();
cntrBean1.setCntrno("cntr1");
JSONArray jsonArrayCntr1 = new JSONArray();
jsonArrayCntr1.add(0, cgoBean1);
cntrBean1.setCgo(jsonArrayCntr1);
//CNTR2
CntrBean cntrBean2 = new CntrBean();
cntrBean2.setCntrno("cntr2");
JSONArray jsonArrayCntr2 = new JSONArray();
jsonArrayCntr2.add(0, cgoBean2);
jsonArrayCntr2.add(1, cgoBean3);
cntrBean2.setCgo(jsonArrayCntr2);
//SIBILL
SiBillBean sibillb = new SiBillBean();
sibillb.setBlno("COSU 123456789");
JSONArray jsonArraySiBill = new JSONArray();
jsonArraySiBill.add(0, cntrBean1);
jsonArraySiBill.add(1, cntrBean2);
sibillb.setCntr(jsonArraySiBill);
System.out.println(JSONObject.fromObject(sibillb));
本源码包内暂不包含可直接显示的源代码文件,请下载源码包。