您的位置:首页 > 移动开发 > Android开发

JSON解析之——Android

2015-12-14 18:46 531 查看
JSON解析之——Android

一、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解析详解
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: