简单的json和bean转换直接用:
public static void main(String[] args) { String s = "{'request': [{'orderCode': 'HOJY20170226000074-O-0','cancelReason': '没有原因'},{'orderCode': 'HOJY20170226000074-O-1','cancelReason': '有原因'}]}"; JSONObject jb = JSONObject.fromObject(s); JSONArray ja = jb.getJSONArray("request"); String orderCode = ja.getJSONObject(1).getString("orderCode"); String cancelReason = ja.getJSONObject(1).getString("cancelReason"); System.out.println(cancelReason+"-----"+orderCode); }
输出结果:有原因-----HOJY20170226000074-O-1
--------------------------------------复杂模式,对象里面有list,比如ReturnOrderDO里面有属性A,B,属性B里面的属性是List<C>,这样直接转就不行报错了,需要用classmap------------------------------------------------------
public static void main(String[] args) { String s = "{'request': [{'returnOrder': {'returnOrderCode': 'RK131','warehouseCode': 'SunEee01'},'orderLines': {'orderLine':[{'ownerCode': 'ownerCode01','itemCode':'itemCode01','planQty': 100},{'ownerCode': 'ownerCode02','itemCode':'itemCode02','planQty': 100}]}}]}"; JSONObject jb = JSONObject.fromObject(s); JSONArray ja = jb.getJSONArray("request"); List<ReturnOrderDO> list = JSONArray.toList(ja,ReturnOrderDO.class); for(ReturnOrderDO one:list){ Map<String, Class> classMap = new HashMap<String, Class>(); classMap.put("orderLine", OrderLine.class); ReturnOrderDO ss = (ReturnOrderDO) JSONObject.toBean(JSONObject.fromObject(one),ReturnOrderDO.class,classMap); System.out.println(ss.getOrderLines().getOrderLine().get(0).getOwnerCode()); }}