【Java】提取JSON數值時遇到數組集合時使用的K-V方式轉換

來源:互聯網
上載者:User

標籤:else   簡單   轉換方法   system   ast   htm   實體類   before   rom   

1.實體類轉換方法

參照文章:http://www.cnblogs.com/dflmg/p/6933811.html

2.K-V方法(此方法比較笨,但是沒有辦法,我現在不知道有沒有相關的簡單API,只能自己手動拼出一個方法。import org.apache.commons.lang.StringUtils;)

String s = "{‘request‘: {‘enterpriseid‘: 55,‘ownerCode‘: ‘SunEee01‘,‘item‘: [{‘itemName‘: ‘1熊孩子新疆無花果成品268g‘,‘itemType‘: ‘ZC‘,‘barCode‘: ‘6924459400256‘,‘shelfLife ‘: 0, ‘itemCode‘: ‘xhzwhggcp_268‘},
{‘itemName‘: ‘2好孩子新疆無花果成品268g‘,‘itemType‘: ‘ZC‘,‘barCode‘: ‘6924459400256‘,‘shelfLife ‘: 1, ‘itemCode‘: ‘xhzwhggcp_268‘}]}}"; //String s = "{‘request‘: {‘enterpriseid‘: 55,‘ownerCode‘: ‘SunEee01‘,‘item‘: [{‘itemName‘: ‘好孩子新疆無花果成品268g‘,‘itemType‘: ‘ZC‘,‘barCode‘: ‘6924459400256‘,‘shelfLife ‘: 1, ‘itemCode‘: ‘xhzwhggcp_268‘}]}}"; JSONObject jsonObject = JSONObject.fromObject(s); //System.out.println(jsonObject); String request = jsonObject.getString("request"); //System.out.println(request); JSONObject vendorDO = JSONObject.fromObject(request); //System.out.println(vendorDO); String ent = vendorDO.getString("item"); //對象實體類的方法System.out.println(ent); /*JSONArray ents = vendorDO.getJSONArray("item"); List<Item> ss = (List<Item>)JSONArray.toList(ents,Item.class); for(Item x:ss){
//如果item裡面還有List對象作為屬性就使用1的方法,參見http://www.cnblogs.com/dflmg/p/6933811.html System.out.println(x.getItemName()); }*/ String[] many = ent.split("\\},\\{"); if(many.length==1){ String one = many[0].substring(1,ent.length()-1); JSONObject joss = JSONObject.fromObject(one); String itemName = joss.getString("itemName"); System.out.println(itemName); }else{ for(int i=0;i<many.length;i++){ if(i==0){ String frist = many[i].substring(1)+"}"; JSONObject joss = JSONObject.fromObject(frist); String itemName = joss.getString("itemName"); System.out.println(itemName); }else if(i==many.length-1){ String middle = "{"+StringUtils.substringBefore(many[i], "]"); JSONObject joss = JSONObject.fromObject(middle); String itemName = joss.getString("itemName"); System.out.println(itemName); }else{ String last = "{"+many[i]+"}"; JSONObject joss = JSONObject.fromObject(last); String itemName = joss.getString("itemName"); System.out.println(itemName); } }}

 

【Java】提取JSON數值時遇到數組集合時使用的K-V方式轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.