zoukankan      html  css  js  c++  java
  • JSON解析之——Android

    JSON解析之——Android

    一、google天气案例

    之前xml学习中的google天气的例子非常形象,所以我们继续以google天气作为案例进行学习,下面是我从google官网下载下来的天气Json文件,可以看出,和xml的格式区别非常大。

     1 {   "coord":{"lon":121.46,"lat":31.22},
     2     "weather":[{
     3         "id":721,
     4         "main":"Haze",
     5         "description":"haze",
     6         "icon":"50d"}],
     7     "base":"stations",
     8     "main":
     9         {"temp":282.15,
    10         "pressure":1024,
    11         "humidity":82,
    12         "temp_min":282.15,
    13         "temp_max":282.15},
    14     "visibility":4500,
    15     "wind":{"speed":5,"deg":310},
    16     "clouds":{"all":44},
    17     "dt":1450060200,
    18     "sys":{
    19         "type":1,
    20         "id":7452,
    21         "message":0.0142,
    22         "country":"CN",
    23         "sunrise":1450046656,
    24         "sunset":1450083169},
    25     "id":1796236,
    26     "name":"Shanghai",
    27     "cod":200
    28  }

     我们需要的数据有:城市 最低温度 最高温度 湿度  风向

    于是我们建立一个CurrentWeatherJson类来存储需要的数据。

     1 package org.xerrard.xmlpulldemo;
     2 
     3 public class CurrentWeatherJson {
     4 
     5     
     6     public String   city;              //城市
     7     public String   temperature_min;       // 温度
     8     public String   temperature_max;       // 温度
     9     public String   humidity;           // 湿度
    10     public String   wind_direction;     // 风向
    11     
    12     public String toString()
    13     {
    14         //摄氏度(℃)=K-273。
    15         float temperatureMin = Float.parseFloat(temperature_min)-272.15f;
    16         float temperatureMax = Float.parseFloat(temperature_max)-272.15f;
    17         
    18         StringBuilder sb = new StringBuilder();
    19         sb.append(" 城市: ").append(city);
    20         sb.append(" 最低温度: ").append(temperatureMin + "").append(" °C");
    21         sb.append(" 最高温度: ").append(temperatureMax + "").append(" °C");
    22         sb.append(" 湿度 ").append(humidity);
    23         sb.append(" 风向 ").append(wind_direction);
    24         return sb.toString();
    25     }
    26 }

    然后我们建立一个数据模型来封装Json数据的解析,在WeatherJsonModel中,我们可以将Json中我们需要的数据解析出来,存储到CurrentWeatherJson对象中

     1 package org.xerrard.xmlpulldemo;
     2 
     3 import org.json.JSONException;
     4 import org.json.JSONObject;
     5 import org.json.JSONTokener;
     6 
     7 public class WeatherJsonModel {
     8 
     9     public static CurrentWeatherJson getData(String json){
    10         JSONTokener jsonParser = new JSONTokener(json);
    11         JSONObject weather;
    12         try {
    13             weather = (JSONObject) jsonParser.nextValue();
    14             if(weather.length()>0){
    15                 CurrentWeatherJson curCondition = new CurrentWeatherJson();
    16                 curCondition.city = weather.getString("name");
    17                 curCondition.humidity = weather.getJSONObject("main").getInt("humidity") + "";
    18                 curCondition.temperature_max = weather.getJSONObject("main").getInt("temp_max") + "";
    19                 curCondition.temperature_min = weather.getJSONObject("main").getInt("temp_min") + "";
    20                 curCondition.wind_direction = weather.getJSONObject("wind").getInt("deg") + "";
    21             }
    22         }
    23         catch (JSONException e) {
    24             // TODO Auto-generated catch block
    25             e.printStackTrace();
    26         }
    27         return curCondition;    
    28         
    29        
    30 
    31     }
    32     
    33 }

    最后,我们可以使用WeatherJsonModel来进行解析数据,并得到我们需要的数据

     1         File jsonFlie = new File(Environment.getExternalStorageDirectory().getPath() + "/" +"weather.json"); 
     2         CharBuffer cbuf = null;  
     3         FileReader fReader;
     4         try {
     5             fReader = new FileReader(jsonFlie);
     6             cbuf = CharBuffer.allocate((int) jsonFlie.length());  
     7             fReader.read(cbuf);  
     8             String text = new String(cbuf.array());  
     9             TextView hello = (TextView)findViewById(R.id.hello);
    10             hello.setText(WeatherJsonModel.getData(text).toString());
    11         }
    12         catch (FileNotFoundException e) {
    13             // TODO Auto-generated catch block
    14             e.printStackTrace();
    15         }
    16         catch (IOException e) {
    17             // TODO Auto-generated catch block
    18             e.printStackTrace();
    19         }  

    二、android中JSON提供的几个比较重要的类

    android的json解析部分都在包org.json下,主要有以下几个类:
    JSONObject:可以看作是一个json对象,这是系统中有关JSON定义的基本单元,其包含一对儿(Key/Value)数值。它对外部(External: 应用toString()方法输出的数值)调用的响应体现为一个标准的字符串(例如:{"JSON": "Hello, World"},最外被大括号包裹,其中的Key和Value被冒号":"分隔)。其对于内部(Internal)行为的操作格式略微,例如:初始化一个JSONObject实例,引用内部的put()方法添加数值:new JSONObject().put("JSON", "Hello, World!"),在Key和Value之间是以逗号","分隔。Value的类型包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object 。

    JSONStringer:json文本构建类 ,根据官方的解释,这个类可以帮助快速和便捷的创建JSON text。其最大的优点在于可以减少由于 格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntax rules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。。其最大的优点在于可以减少由于格式的错误导致程序异常,引用这个类可以自动严格按照JSON语法规则(syntax rules)创建JSON text。每个JSONStringer实体只能对应创建一个JSON text。

    JSONArray:它代表一组有序的数值。将其转换为String输出(toString)所表现的形式是用方括号包裹,数值以逗号”,”分隔(例如: [value1,value2,value3],大家可以亲自利用简短的代码更加直观的了解其格式)。这个类的内部同样具有查询行为, get()和opt()两种方法都可以通过index索引返回指定的数值,put()方法用来添加或者替换数值。同样这个类的value类型可以包括:Boolean、JSONArray、JSONObject、Number、String或者默认值JSONObject.NULL object。

    JSONTokener:json解析类
    JSONException:json中用到的异常

     三、对于复杂的JSON数据的解析,google提供了Gson来处理。

    参考资料:

    google weather api : http://openweathermap.org/current

    http://blog.csdn.net/onlyonecoder/article/details/8490924  android JSON解析详解

  • 相关阅读:
    SpringMVC开发环境搭建
    SpringMVCRestful
    SpringMVC源码执行流程
    SpringMVC域对象数据输出
    SpringMVC请求参数
    Object类常用方法
    五大浏览器
    jinja2的学习之路
    嚣张过后之解决问题篇(无果)
    嚣张狂妄的经历之二(应聘infosys的teamleader)
  • 原文地址:https://www.cnblogs.com/xerrard/p/5022716.html
Copyright © 2011-2022 走看看