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. Windows系统下的TCP参数优化

    1. TCP连接的状态 首先介绍一下TCP连接建立与关闭过程中的状态.TCP连接过程是状态的转换,促使状态发生转换的因素包括用户调用.特定数据包以及超时等,具体状态如下所示: CLOSED:初始状态, ...

  2. Android Task 相关

    在日常开发过程中,只要涉及到activity,那么对task相关的东西总会或多或少的接触到,不过对task相关的一些配置的作用一直理解的还不是很透彻,官方文档在细节上说的也不够清楚,要透彻理解还是得自 ...

  3. Flesch Reading Ease(模拟)

    http://poj.org/problem?id=3371 终于遇到简单一点的模拟题了.不过本人真心没有耐心读题目... 它的大致意思就是给一段合法的文章,求出这段文章的单词数,句子数,音节数,按照 ...

  4. 开源代码搜索器searchcode

    项目主页:https://searchcode.com/ 查看API:https://searchcode.com/api/ 关于:https://searchcode.com/about/ Sear ...

  5. Linux系统下UDP发送和接收广播消息小例子

    // 发送端 #include <iostream> #include <stdio.h> #include <sys/socket.h> #include < ...

  6. 【STL】【模拟】Codeforces 696A Lorenzo Von Matterhorn

    题目链接: http://codeforces.com/problemset/problem/696/A 题目大意: 一个满二叉树,深度无限,节点顺序编号,k的儿子是k+k和k+k+1,一开始树上的边 ...

  7. floyd详解

    就不在来回搬了 请看 http://note.youdao.com/groupshare/?token=6422E952998F4381A1534B71359EFA57&gid=1579165 ...

  8. zoj 3365 灵活数字规律

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3365 #include <cstdio> #incl ...

  9. ovs router

  10. Appium移动自动化测试(四)--one demo(转)

    Appium移动自动化测试(四)--one demo 2015-06-15 20:41 by 虫师, 40514 阅读, 34 评论, 收藏, 编辑 继续更新. ------------------- ...