JAVA 解析JSON格式数据

      1.解析JSON格式数据需要的JAR包:

      commons-beanutils.jar

      commons-collections-3.1.jar

      commons-lang-2.0.jar

      commons-logging.jar

      ezmorph-1.0.6.jar

      json-lib-2.4-jdk15.jar

      log4j-1.2.11.jar

      morph-1.1.1.jar

      附件提供下载。

    

      2. 解析数据核心代码(附件2有淘宝返回的JSON格式数据示例)

Java代码   收藏代码
  1. /** 
  2.      * 解析从淘宝返回的订单详情数据 
  3.      * @param jsonString:淘宝返回的JSON格式数据 
  4.      * @return:订单详情数据 
  5.      */  
  6.     public Order analyticJson(String jsonString){  
  7.   
  8.         //JSON格式数据解析对象  
  9.         JSONObject jb = JSONObject.fromObject(jsonString);    
  10.         JSONObject ja = jb.getJSONObject("trade_fullinfo_get_response").getJSONObject("trade");  
  11.           
  12.         //需返回的订单对象  
  13.         Order order = new Order();  
  14.           
  15.         order.setBuyer_nick(ja.getString("buyer_nick"));  
  16.         order.setReceiver_address(ja.getString("receiver_address"));  
  17.         order.setReceiver_city(ja.getString("receiver_city"));  
  18.         order.setReceiver_name(ja.getString("receiver_name"));  
  19.         order.setReceiver_state(ja.getString("receiver_state"));  
  20.           
  21.         //区域是否存在  
  22.         if(ja.containsKey("receiver_district")){  
  23.             order.setReceiver_district(ja.getString("receiver_district"));  
  24.         }else{  
  25.             order.setReceiver_district("");  
  26.         }  
  27.         //手机号是否存在  
  28.         if(ja.containsKey("receiver_mobile")){  
  29.             order.setReceiver_mobile(ja.getString("receiver_mobile"));  
  30.         }else{  
  31.             order.setReceiver_mobile("");  
  32.         }  
  33.         //电话是否存在  
  34.         if(ja.containsKey("receiver_phone")){  
  35.             order.setReceiver_phone(ja.getString("receiver_phone"));  
  36.         }else{  
  37.             order.setReceiver_phone("");  
  38.         }  
  39.           
  40.         //订单明细列表  
  41.         java.util.List<OrderDetail> goodsList = new java.util.LinkedList<OrderDetail>();  
  42.         JSONArray orderDetailArr = ja.getJSONObject("orders").getJSONArray("order");  
  43.           
  44.         //循环添加订单明细  
  45.         for(int j=0;j<orderDetailArr.size();j++){  
  46.             OrderDetail od = new OrderDetail();  
  47.             od.setNum(orderDetailArr.getJSONObject(j).getString("num"));  
  48.             od.setOuter_iid(orderDetailArr.getJSONObject(j).getString("outer_iid"));  
  49.             od.setPayment(orderDetailArr.getJSONObject(j).getString("payment"));  
  50.             goodsList.add(od);  
  51.         }  
  52.         order.setGoodsList(goodsList);  
  53.   
  54.         return order;  
  55.               
  56.     } 

你可能感兴趣的:(java,解析JSON格式数据)