Android下Json数据解析

如从网络获取JSON 则需要创建一个工具类,该类返回一个字符串为JSON文本

package com.example.jsonapp;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;



public class UrlHtmlUtil {
     public static String getHtmlJsonByUrl(String urlTemp){
        URL url = null;
        InputStreamReader input = null; 
        HttpURLConnection conn;
      //  JSONObject jsonObj = null;
        String a = null;
        try {
           url = new URL(urlTemp);
           conn = (HttpURLConnection) url.openConnection();
           input = new InputStreamReader(conn.getInputStream(),"utf-8");
           Scanner inputStream = new Scanner(input);   
           StringBuffer sb = new StringBuffer();
           while (inputStream.hasNext()) {    
                 sb.append(inputStream.nextLine());
           }
            a=sb.toString();
    
       } catch (Exception e) {  
            System.out.println(e.getMessage());
      }
  
         return a;
  
 }

 
}
然后将文本转为JSONArray,用JSONArray.optJSONObject()来获取JSONObject 对象,接下来便可解析

JSONArray array=new JSONArray(json);
						Log.i("转换数组成功","");
						for(int i=0;i<array.length();i++)
						{
							 JSONObject jo = array.optJSONObject(i);
							if(jo.getString("area").equals(cityName))
							{
								tv.setText("AQI指数:"+jo.getString("aqi")+"\n地区:"+jo.getString("area")
										+"\n空气质量:"+jo.getString("quality"));
								
							break;}
							if(i==array.length()-1){
							tv.setText("抱歉,也并没有找到该城市");
							}
						}


public void enJson(String json){
	
		try {
			JSONTokener jsonParser=new JSONTokener(json);
			JSONObject aqi=(JSONObject)jsonParser.nextValue();
			String aqistr,areastr,quastr,lvstr,timestr;
			aqistr=aqi.getString("aqi");
			areastr=aqi.getString("area");
			quastr=aqi.getString("quality");
			lvstr=levelToLevel(aqi.getString("level"));
			timestr=timeToTime(aqi.getString("time"));
			
			tv.setText("地区:"+areastr+"\nAQI:"+aqistr+"\n空气质量:"+quastr+"\n小贴士:"+lvstr+"\n更新时间:"+timestr+"\n点我刷新数据");
			
		}


posted on 2015-03-22 16:07  木鱼哥  阅读(100)  评论(0编辑  收藏  举报

导航