用JSONObject和JSONArray 解析json数据
发布时间:2020-12-16 18:50:32 所属栏目:百科 来源:网络整理
导读:json数据: { "resultcode": "200","reason": "SUCCESSED!","result": [ { "city": "苏州","PM2.5": "73","AQI": "98","quality": "良","PM10": "50","CO": "0.79","NO2": "65","O3": "28","SO2": "41","time": "2014-12-26 11:48:40" } ],"error_code": 0}
json数据: { "resultcode": "200","reason": "SUCCESSED!","result": [ { "city": "苏州","PM2.5": "73","AQI": "98","quality": "良","PM10": "50","CO": "0.79","NO2": "65","O3": "28","SO2": "41","time": "2014-12-26 11:48:40" } ],"error_code": 0 } 解析数据代码: JSONObject jsonObject = new JSONObject(result); int resultCode = jsonObject.getInt("resultcode"); if (resultCode == 200) { JSONArray resultJsonArray = jsonObject.getJSONArray("result"); JSONObject resultJsonObject = resultJsonArray.getJSONObject(0);//如果是用第一个对象就如下所写的,如果是数组就用循环,在新建一对象resultJsonObject String output = resultJsonObject.getString("city"); resultJsonObject.getString("PM2.5") ; resultJsonObject.getString("AQI"); resultJsonObject.getString("quality"); resultJsonObject.getString("PM10"); resultJsonObject.getString("CO") ; resultJsonObject.getString("NO2") ; resultJsonObject.getString("O3") ; resultJsonObject.getString("SO2") ; resultJsonObject.getString("time"); } json数据: { "crset":[ { "merchantname":"三火餐厅","menu":[ { "menuid":"1","menuname":"酸菜鱼" },{ "menuid":"2","menuname":"麻婆豆腐" },{ "menuid":"3","menuname":"酸菜鱼" } ] },{ "merchantname":"粤菜餐厅","menuname":"炒生菜" },"menuname":"蒸鱼" },"menuname":"煎豆腐" } ] },{ "merchantname":"西式餐厅","menuname":"牛扒" },"menuname":"罗宋汤" },"menuname":"三文治" } ] } ] } 生成实体类: public class Merchants { private List<Merchant> merchant; } public class Merchant{ private String merchantname; private List<Menu> menu; } public class Menu { private String menuid; private String menuname; } 解析数据如下 JSONObject jsonObject = new JSONObject(json);// json上方返回的数据 JSONArray jsonArray =jsonObject.getJSONArray("crset"); List<Merchant> merchants = new ArrayList<Merchant>(); for(int i = 0;i<jsonArray.length();i++) { // 解析每个merchant JSONObject item = jsonArray.getJSONObject(i); Merchant merchant = new Merchant(); merchant.setMerchantname(item.getString("merchantname")); // 解析每个menu List<Menu> menus = new ArrayList<Menu>(); JSONArray array = item.getJSONArray("menu"); for (int j = 0; j < array.length(); j++) { JSONObject menuitem = array.getJSONObject(i); Menu menu = new Menu(); menu.setMenuid(menuitem.getString("menuid")); menu.setMenuname(menuitem.getString("menuname")); menus.add(menu); } merchant.setMenu(menus); merchants.add(merchant); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |