基本概念
首先看一下一些json方面基本概念:
json的定义
json定义为一种轻量级的数据交换格式,具有良好的可读性和便于快捷编写的特征。业内主流技术为其提供了完整的解决方案,获得了当今大部分语音的支持,从而可以再不同平台间进行数据交换。
json 与xml的比较
1、json和xml都具有良好的可读性优点,其可读性基本相同;
2、json和xml同样拥有丰富的解析手段;
3、json相对于xml,其数据的体积较小;
4、json与javascript的交互更加方便;
5、json对数据的描述性比xml较差;
6、json的速度要远远快于xml。
android对json的解析
相关类说明:
JSONObject:可以看做一个json对象,是系统中有关json定义的基本单元,包含一对键值对。
JSONStringer:json文本构建类,帮助快速与便捷地创建JSON text。
JSONArray:JSON数组,包含一组有序的JSONObject。
JSONTokener:json解析类
JSONException:json中用到的异常
使用org.json包JSONOBject和JSONArray进行解析
常见类型例子解析
{ "name" : "sam" , "age" :18, "weight" :60} |
| [{ "name" : "sam" , "age" :18},{ "name" : "leo" , "age" :19},{ "name" : "sky" , "age" :20}] |
第一个json对象json1的解析
1 | JSONObject jsonObj = new JSONObject(json1); |
2 | String name = jsonObj.optString( "name" ); |
3 | int age = jsonObj.optInt( "age" ); |
4 | int weight = jsonObj.optInt( "weight" ); |
另外还有
1 | Object opt(String name) |
2 | boolean optBoolean(String name) |
3 | double optDouble(String name) |
4 | JSONArray optJSONArray(String name) |
5 | JSONObject optJSONObject(String name) |
等方法,我推荐用这些方法,这些方法在解析时,如果对应字段不存在会返回空值或者0,不会报错。
当然如果你使用以下方法
1 | Object get(String name) |
2 | boolean getBoolean(String name) |
3 | int getInt(String name) |
等方法时,代码不会去判断是否存在该字段,需要你自己去判断,否则的话会报错。自己判断的话使用has(String name)
来判断。
再来看解析数组,简单的数组。第二个json2
1 | JSONArray jsonArray = new JSONArray(json2); |
2 | for ( int = 0 ; i < jsonArray.length();i++) { |
3 | int age = jsonArray.optInt(i); |
解析复杂数组,包含对象,json3
1 | JSONArray jsonArray = new JSONArray(json3); |
2 | for ( int = 0 ; i < jsonArray.length();i++) { |
3 | JSONObject jsonObject = jsonArray.optJSONObject(i); |
4 | String name = jsonObject.optString( "name" ); |
5 | int age = jsonObject.optInt( "age" ); |
使用JsonReader进行解析
JsonReader的使用其实和xml解析中的pull是有一点类似的,我们来看示例。
前面的JSONObject和JSONArray创建时传的是String,而JsonReader需要传入的时候是Reader,网络访问中,我们可以直接拿输入流传进来,转成Reader。我们这里假设我们上面的String已经转成InputStream了,分别为jsonIs1,jsonIs2,jsonIs3。
上面的json1解析:
01 | JsonReader reader = new JsonReader( new InputStreamReader(jsonIs1)); |
02 | try {积分: 49 排名:第 1495693 名上传资源: 1 |
04 | while (reader.hasNext()) { |
05 | String keyName = reader.nextName(); |
06 | if (keyName.equals( "name" )) { |
07 | String name = reader.nextString(); |
08 | } else if (keyName.equals( "age" )) { |
09 | int age = reader.nextInt(); |
10 | } else if (keyName.equals( "weight" )) { |
11 | int weight = reader.nextInt(); |
上面json2的解析:
01 | JsonReader reader = new JsonReader( new InputStreamReader(jsonIs2)); |
03 | List<Integer> ages = new ArrayList<Integer>(); |
05 | while (reader.hasNext()) { |
06 | ages.add(reader.nextInt()); |
参考文章: