zoukankan      html  css  js  c++  java
  • 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")+"
    地区:"+jo.getString("area")
    										+"
    空气质量:"+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+"
    AQI:"+aqistr+"
    空气质量:"+quastr+"
    小贴士:"+lvstr+"
    更新时间:"+timestr+"
    点我刷新数据");
    			
    		}


  • 相关阅读:
    TreeView checkbox
    学习wcf
    Python导入其他目录的模板
    xcode中如何设置编译后的app路径
    python中package机制的两种实现方式
    Page Object封装思想
    mac xcworkspace xcodebuild
    mac软件管理软件HomeBrew
    app被Rejected 的各种原因翻译
    scan-build static analyze help
  • 原文地址:https://www.cnblogs.com/muyuge/p/6333588.html
Copyright © 2011-2022 走看看