当前位置: 代码迷 >> Java Web开发 >> 这种格式的json用struts2如何转
  详细解决方案

这种格式的json用struts2如何转

热度:51   发布时间:2016-04-16 22:15:00.0
这种格式的json用struts2怎么转?
{"total":28,"rows":[
{"productid":"FI-SW-01","unitcost":10.00,"status":"P","listprice":36.50,"attr1":"Large","itemid":"EST-1"},
{"productid":"K9-DL-01","unitcost":12.00,"status":"P","listprice":18.50,"attr1":"Spotted Adult Female","itemid":"EST-10"},
{"productid":"RP-SN-01","unitcost":12.00,"status":"P","listprice":28.50,"attr1":"Venomless","itemid":"EST-11"},
{"productid":"RP-SN-01","unitcost":12.00,"status":"P","listprice":26.50,"attr1":"Rattleless","itemid":"EST-12"},
{"productid":"RP-LI-02","unitcost":12.00,"status":"P","listprice":35.50,"attr1":"Green Adult","itemid":"EST-13"},
{"productid":"FL-DSH-01","unitcost":12.00,"status":"P","listprice":158.50,"attr1":"Tailless","itemid":"EST-14"},
{"productid":"FL-DSH-01","unitcost":12.00,"status":"P","listprice":83.50,"attr1":"With tail","itemid":"EST-15"},
{"productid":"FL-DLH-02","unitcost":12.00,"status":"P","listprice":63.50,"attr1":"Adult Female","itemid":"EST-16"},
{"productid":"FL-DLH-02","unitcost":12.00,"status":"P","listprice":89.50,"attr1":"Adult Male","itemid":"EST-17"},
{"productid":"AV-CB-01","unitcost":92.00,"status":"P","listprice":63.50,"attr1":"Adult Male","itemid":"EST-18"}
],"footer":[
{"unitcost":19.80,"listprice":60.40,"productid":"Average:"},
{"unitcost":198.00,"listprice":604.00,"productid":"Total:"}
]}

用JSONArray.fromObject会报错,提示必须用[]开头和结尾。
------解决方案--------------------

JSONObject jsonObject = JSONObject.fromObject(str);
String total = jsonObject .getString("total ");
JSONArray rowsArray = jsonObject.getJSONArray("rows");
for (int i = 0; i <rowsArray .size(); i++) {
    JSONObject jsonRows = JSONObject.fromObject(rowsArray .get(i));
    String productid = jsonRows.getString("productid");
     ......
 }
JSONArray footerArray = jsonObject.getJSONArray("footer");
for (int i = 0; i <footerArray .size(); i++) {
    JSONObject jsonFooter = JSONObject.fromObject(footerArray .get(i));
    String unitcost = jsonRows.getString("unitcost");
     ......
 }

------解决方案--------------------
写上对应的java bean 用开源的jar 开源转 。json 转 bean 。
bean 转json .
------解决方案--------------------
JSONArray.fromObject这个是转化为jsonarray数组,你那明显是jsonobject,用JSONObject.fromObject才行
  相关解决方案