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解析详解

JSON解析之——Android的更多相关文章

  1. android json解析及简单例子

    JSON的定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据 ...

  2. [Android]天气App 3 网络数据的请求和Json解析

      Android客户端开发,不仅仅是在Android端开发,还需要有相应的后台服务支持,否则的话,客户端的数据就只能放到本地自己做处理.我认为的原生态的App就是对应服务端的Client.他能像浏览 ...

  3. android Json解析详解

    JSON的定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语 言的支持),从而可以在不同平台间进行数 ...

  4. android Json解析详解(详细代码)

    JSON的定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据 ...

  5. 【转】android json解析及简单例子

    JSON的定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据 ...

  6. jsonObject jsonArray jsonTokener jsonStringer,json解析以及http请求获取josn数据并加以解析

    JSON的定义: 一 种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的 支持),从而可以在不同平台间进行 ...

  7. Android okHttp网络请求之Json解析

    前言: 前面两篇文章介绍了基于okHttp的post.get请求,以及文件的上传下载,今天主要介绍一下如何和Json解析一起使用?如何才能提高开发效率? okHttp相关文章地址: Android o ...

  8. Android之JSON解析

    做个Android网络编程的同学一定对于JSON解析一点都不陌生,因为现在我们通过手机向服务器请求资源,服务器给我们返回的数据资源一般都是以JSON格式返回,当然还有一些通过XML格式返回,相对JSO ...

  9. android JSON解析之JSONObject与GSON

    1.写在前面 JSON数据是android网络开发中常见的数据格式,JSON最常见的传输方法是使用HTTP协议,关于android开发中HTTP协议的使用方法可参考我的另一篇随笔android网络编程 ...

随机推荐

  1. Jump

    hdu4862:http://acm.hdu.edu.cn/showproblem.php?pid=4862 题意:给你n*m的方格,每个方格中有一个数(0---9),然后你每次可以选择一个点开始,这 ...

  2. 设置Tomcat默认界面

    修改配置文件:         首先,修改$tomcat/conf/server.xml文件.      在server.xml文件中,有一段如下:      ……      <engine   ...

  3. 【HDOJ】2405 Marbles in Three Baskets

    BFS+状态压缩. /* 2405 */ #include <iostream> #include <queue> #include <cstdio> #inclu ...

  4. ural-1099-Work Scheduling(裸带花树)

    题意: 有N个人,有限对的人可以在一起工作,问最多能有多少对. 分析: 任意图的最大匹配 // File MAXName: 1099.cpp // Author: Zlbing // Created ...

  5. weblogic启动报错之WLS_DIAGNOSTICS000000.DAT

    查看控制台日志报错信息如下: <-- 下午04时46分42秒 CST> <Notice> <Log Management> <BEA-> <The ...

  6. 调用系统api修改系统时间

    一:截图 二:代码 using System; using System.Collections.Generic; using System.ComponentModel; using System. ...

  7. 加密解密,CryptoStream()的使用

    一:上图 二:代码 主界面代码 using System; using System.Collections.Generic; using System.ComponentModel; using S ...

  8. Android *.db-journal

    config.xml <!-- The default journal mode to use use when Write-Ahead Logging is not active. Choic ...

  9. C# 匿名方法 委托 Action委托 Delegate委托

    原文地址:https://msdn.microsoft.com/zh-cn/library/bb882516.aspx 匿名函数是一个“内联”语句或表达式,可在需要委托类型的任何地方使用. 可以使用匿 ...

  10. 【转】Linux下查看所有用户及用户组

    groups 查看当前登录用户的组内成员groups gliethttp 查看gliethttp用户所在的组,以及组内成员whoami 查看当前登录用户名/etc/group文件包含所有组/etc/s ...