Android中JSON解析

 try {
			InputStream is = getAssets().open("city.txt");
			String json = Utils.readIputStream(is);
			//解析json数据
			JSONObject result = new JSONObject(json);
			JSONObject obj = result.getJSONObject("result");//result是city中的字段
			for (int i = 0; i < letters.length; i++) {
				/**
				 * 先判断这个字母有没有对应的数据
				 */
				if (obj.has(letters[i])) {
					/**
					 * 有的话,就进行乡下解析,city中下面的是一个数组
					 */
					JSONArray array = obj.getJSONArray(letters[i]);
					int len = array.length();
					mList.add(letters[i]);
					for(int j= 0;j<len;j++){
						JSONObject o = array.getJSONObject(j);
						City city = new City();
						city.name = o.getString("name");
						city.code = o.getString("code");
						mList.add(city);
					}
				}
			}
			cityAdapter  mAdapter = new cityAdapter();
			 mListView.setAdapter(mAdapter);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		 
	}	

Utils 类中输入输出流代码

public class Utils {

	public static String readIputStream(InputStream is) throws IOException {
		String json = null;
	    byte [] buff = new byte[1024];
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int len = 0;
		while((len = is.read(buff))!=-1){
			
			baos.write(buff,0,len);
		}
		baos.flush();
		baos.close();
		is.close();
		json = new String(baos.toByteArray(),"utf-8");
		
		return json;
	}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值