Json数据解析

    |     2015年8月11日   |   网络通讯   |     0 条评论   |    1736

Json是一种轻量级的数据交换格式,采用完全独立于语言的文本格式.易于阅读和编写,同时也易于机器解析和生成.支持多种语言包括C, C++, C#, Java, JavaScript, Perl, Python等).

JSON书写格式

JSON的规则很简单:对象是一个无序的“‘名称/值’对”集合。
一个对象以“{”(左括号)开始,“}”(右括号)结束 每个“名称”后跟一个“:”(冒号) “‘名称/值’对”之间使用“,”(逗号)分隔。

微信截图_20210412105246

 

规则如下:
1) 映射用冒号(“:”)表示。名称:值
2) 并列的数据之间用逗号(“,”)分隔。名称1:值1,名称2:值2
3) 映射的集合(对象)用大括号(“{}”)表示。{名称1:值,名称2:值2}
4) 并列数据的集合(数组)用方括号(“[]”)表示。
[
{名称1:值,名称2:值2},
{名称1:值,名称2:值2}
]
5)元素值可具有的类型:string, number, object, array, true, false, null

例子

例1、{ "name": "Obama"}

例2、{ "name": "Romney","age": 56}

例3、{ "city":{"name": "bj"},"weatherinfo":{"weather": "sunny"}}

例4、{
"city":{"name": "北京",“city_id”:"101010100"},
"weatherinfo":{"weather": "sunny","temp":"29度"}
}
例5、
[
  { "name": "张三", "age":22, "email": "zhangsan@qq.com" },
  { "name": "李四", "age":23, "email": "lisi@qq.com"},
  { "name": "王五", "age":24, "email": "wangwu@qq.com" }
]

例6、
{ "student":
  [
    { "name": "张三", "age":22, "email": "zhangsan@qq.com" },
    { "name": "李四", "age":23, "email": "lisi@qq.com"},
    { "name": "王五", "age":24, "email": "wangwu@qq.com" }
  ]
}

在Android中使用json

JSONObject解析举例
在服务器上有一个html文件http://www.weather.com.cn/data/sk/101010100.html
html内容如下:

{"weatherinfo":
   {"city":"北京","cityid":"101010100","temp":"21","WD":"东南风"
    ,"WS":"2  级","SD":"78%","WSE":"2","time":"21:10","isRadar":"1"
    ,"Radar":"JC_RADAR_AZ9010_JB"}
}

解析步骤
1、读取html文件源代码,获取一个json字符串

InputStream in = conn.getInputStream();
String jsonStr = DataUtil.Stream2String(in);//将流转换成字符串的工具类

2、通过构造函数将json字符串转换成json对象

JSONObject  jsonObject=new JSONObject(jsonStr);

3、从json对象中获取你所需要的键所对应的值

JSONObject  json=jsonObject.getJSONObject("weatherinfo");
String city=json.getString("city");
String temp=json.getString("temp")

JSONArray解析举例
在服务器上有一个js文件http://192.168.1.101/Web/news.js文件内容如下:

[
 {
   title : "国家发改委:台湾降油价和大陆没可比性",
   description : "国家发改委副主任朱之鑫",
   image : "http://192.168.1.101/Web/img/a.jpg",
   comment : 163
 },
 {
  title : "国家发改委:台湾降油价和大陆没可比性",
  description : "国家发改委副主任朱之鑫",
  image : "http://192.168.1.101/Web/img/b.jpg",
  comment : 0
 },
 {
   title : "国家发改委:台湾降油价和大陆没可比性",
   description : "国家发改委副主任朱之鑫",
   image : "http://192.168.1.101/Web/img/c.jpg",
   comment : 0
 }
];

解析步骤
1、读取文件源代码,获取一个json字符串

String jsonStr = DataUtil.Stream2String(in);

2、通过构造函数将json字符串转换成json数组

JSONArray array = new JSONArray(jsonStr);

3、遍历数组,获取数组中每一个json对象,同时可以获取json对象中键对应的值

for (int i = 0; i < array.length(); i++) {
   JSONObject obj = array.getJSONObject(i);
   String title=obj.getString("title");
   String description=obj.getString("description");
}

注意: 1、json数组并非全是由json对象组成的数组
2、json数组中的每一个元素数据类型可以不相同

如何将一个json对象转换成json字符串?

        Logs.d("=========生成json数组字符串========================");
	JSONObject j1 = new JSONObject();
	j1.put("userName", "张三");
	j1.put("passWord", "123456");

	JSONObject j2 = new JSONObject();
	j2.put("userName", "李四");
	j2.put("passWord", "abcd");

	JSONArray array = new JSONArray();
	array.put(0, j1);
	array.put(1, j2);
	Logs.v(array.toString());

	Logs.d("=========解析json数组========================");
	for(int i = 0; i<array.length(); i++){
		JSONObject jsonObject = array.getJSONObject(i);
		String userName = jsonObject.getString("userName");
	        String passWord = jsonObject.getString("passWord");
		Logs.v("userName :"+userName+", passWord :"+passWord);

	}

}

fastjson生成和解析json数据

(举例:4种常用类型:JavaBean,List,List,List<Map<String,Object>)

fastjson简介:
Fastjson是一个Java语言编写的高性能功能完善的JSON库。fastjson采用独创的算法,将parse的速度提升到极致,超过所有json库,包括曾经号称最快的jackson。并且还超越了google的二进制协议protocol buf。Fastjson完全支持http://json.org的标准,也是官方网站收录的参考实现之一。支持各种JDK类型。包括基本类型、JavaBean、Collection、Map、Enum、泛型等。支持JDK 5、JDK 6、Android、阿里云手机等环境。

一. fastjson生成json字符串(JavaBean,List,List,List<Map<String,Object>)

   String jsonStrng = JSON.toJSONString(object);

二. fastjson 解析json字符串为四种类型

  
     1. JavaBean

          Person person = JSON.parseObject(jsonString, Person.class);

      2. List<JavaBean>

          List<Person> listPerson =JSON.parseArray(jsonString, Person.class);

      3. List<String>

          List<String> listString = JSON.parseArray(jsonString, String.class);

      4. List<Map<String,Object>>

 

参考:
JSON官网
FastJson

 

Object References

Consider the following JSON.

{
  'authors': [
    {
      'id': 1,
      'name': 'Joshua Bloch'
    },
    {
      'id': 2,
      'name': 'Neal Gafter'
    }
  ],
  'books': [
    {
      'title': 'Java Puzzlers: Traps, Pitfalls, and Corner Cases',
      'isbn': '032133678X',
      'authors':[1, 2]
    },
    {
      'title': 'Effective Java (2nd Edition)',
      'isbn': '0321356683', 
      'authors':[1]
    }
  ]
}

The JSON object shown above comprise two authors and two books. The books have a reference to the authors through their ids as in this example the books’ field authors only contains the authors’ ids. This is quite a common scenario as this approach will reduce the size of the JSON object as duplicate objects are referred to by their id. The following image captures the new JSON object hierarchy.

 

转载请注明来源:Json数据解析
回复 取消