JSON解析之——Android
2015-12-14 18:46
531 查看
JSON解析之——Android
我们需要的数据有:城市 最低温度 最高温度 湿度 风向
于是我们建立一个CurrentWeatherJson类来存储需要的数据。
然后我们建立一个数据模型来封装Json数据的解析,在WeatherJsonModel中,我们可以将Json中我们需要的数据解析出来,存储到CurrentWeatherJson对象中
最后,我们可以使用WeatherJsonModel来进行解析数据,并得到我们需要的数据
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解析详解
一、google天气案例
之前xml学习中的google天气的例子非常形象,所以我们继续以google天气作为案例进行学习,下面是我从google官网下载下来的天气Json文件,可以看出,和xml的格式区别非常大。{ "coord":{"lon":121.46,"lat":31.22}, "weather":[{ "id":721, "main":"Haze", "description":"haze", "icon":"50d"}], "base":"stations", "main": {"temp":282.15, "pressure":1024, "humidity":82, "temp_min":282.15, "temp_max":282.15}, "visibility":4500, "wind":{"speed":5,"deg":310}, "clouds":{"all":44}, "dt":1450060200, "sys":{ "type":1, "id":7452, "message":0.0142, "country":"CN", "sunrise":1450046656, "sunset":1450083169}, "id":1796236, "name":"Shanghai", "cod":200 }
我们需要的数据有:城市 最低温度 最高温度 湿度 风向
于是我们建立一个CurrentWeatherJson类来存储需要的数据。
package org.xerrard.xmlpulldemo; public class CurrentWeatherJson { public String city; //城市 public String temperature_min; // 温度 public String temperature_max; // 温度 public String humidity; // 湿度 public String wind_direction; // 风向 public String toString() { //摄氏度(℃)=K-273。 float temperatureMin = Float.parseFloat(temperature_min)-272.15f; float temperatureMax = Float.parseFloat(temperature_max)-272.15f; StringBuilder sb = new StringBuilder(); sb.append(" 城市: ").append(city); sb.append(" 最低温度: ").append(temperatureMin + "").append(" °C"); sb.append(" 最高温度: ").append(temperatureMax + "").append(" °C"); sb.append(" 湿度 ").append(humidity); sb.append(" 风向 ").append(wind_direction); return sb.toString(); } }
然后我们建立一个数据模型来封装Json数据的解析,在WeatherJsonModel中,我们可以将Json中我们需要的数据解析出来,存储到CurrentWeatherJson对象中
package org.xerrard.xmlpulldemo; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; public class WeatherJsonModel { public static CurrentWeatherJson getData(String json){ JSONTokener jsonParser = new JSONTokener(json); JSONObject weather; try { weather = (JSONObject) jsonParser.nextValue(); if(weather.length()>0){ CurrentWeatherJson curCondition = new CurrentWeatherJson(); curCondition.city = weather.getString("name"); curCondition.humidity = weather.getJSONObject("main").getInt("humidity") + ""; curCondition.temperature_max = weather.getJSONObject("main").getInt("temp_max") + ""; curCondition.temperature_min = weather.getJSONObject("main").getInt("temp_min") + ""; curCondition.wind_direction = weather.getJSONObject("wind").getInt("deg") + ""; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return curCondition; } }
最后,我们可以使用WeatherJsonModel来进行解析数据,并得到我们需要的数据
File jsonFlie = new File(Environment.getExternalStorageDirectory().getPath() + "/" +"weather.json"); CharBuffer cbuf = null; FileReader fReader; try { fReader = new FileReader(jsonFlie); cbuf = CharBuffer.allocate((int) jsonFlie.length()); fReader.read(cbuf); String text = new String(cbuf.array()); TextView hello = (TextView)findViewById(R.id.hello); hello.setText(WeatherJsonModel.getData(text).toString()); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
二、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解析详解
相关文章推荐
- Android蓝牙BLE之RSSI读写(2)
- Android学习之高德地图 一(定位)
- Crazy Android Note Chapter-7
- android选择图片得到实际路径的总结
- Android蓝牙BLE之RSSI数据的读写(1)
- 自定义switch控件
- MPAndroidChart 教程:坐标轴,X轴,Y轴,Labels(三)
- android十大开源项目
- Android 5.0 隐藏状态栏和导航栏
- Android 百分比布局库(percent-support-lib) 解析与扩展
- Android Studio 多渠道打包(二)
- 教你如何用Android画一个几何图形
- Android
- Android Ndk 编译
- Android之怎么隐藏EditText光标和自动显示键盘
- Android System Property系统属性说明
- 解决Android Studio代码提示快捷键冲突
- 查看Android签名信息
- SkylineGlobe Android 开发 面积计算示例代码
- android获取系统相关信息(后续更新)