Json的介绍:http://www.json.org/
Json解析库gson: http://code.google.com/p/google-gson/
什么是JSON?Json是干什么的?它究竟有什么的么用?对于初学者来说它就像是一个看不懂的大姑娘,对它无从下手,一看就认为很难,所以会对它产生抵触心理,尤其是身为一个中国人,对英文源码更是一个头两个大了。没关系,你们的福利来了,我也是刚刚接触JSON,通过自学,也有了自己的一点理解,希望可以帮到想了解JSON的朋友们,一点浅薄的意见希望笑纳,若有更多的交流意见欢迎指证,共同进步
一,定义
通过查看源码
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C、C++、C#、Java、JavaScript、Perl、Python等)。这些特性使JSON成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率)。
简单来说就是一种数据交换的格式,它有自己独有的方式,因为它比较容易接受,所以就被广泛应用。
二,JSON 语法规则
-
数据在键值对中
-
数据由逗号分隔
-
花括号保存对象
-
方括号保存数组
三,JSON解析的格式
我们在安卓中看到的文本格式一般都是xml格式的文件,而JSON并没有多么复杂,就是普通的文本格式,最后要提交给用户界面看到的都是需要转化为字符串形式。JSON解析一共有四种格式:
(1)就是一个对象格式{, , , , }
(2)就是一个数组
(3)数组中有数组[{ ,,},{,,}]
(4)对象中有数组
如果你还是没有明白的话,可以简单总结一下,JSON其实就是另外一种文本转换的格式,通常与网络请求时联系在一起使用的。
四,json解析数据的两种方法
(1)使用Android中的JSONObject和JSONArray解析json数据
String strJson = "{\"students\":[{\"name\":\"Lucy\",\"age\":12}, {\"name\":\"Tom\",\"age\":23},
{\"name\":\"Niki\",\"age\":22}, {\"name\":\"Linda\",\"age\":31}]}";
try {
JSONObject object = new JSONObject(strJson);
JSONArray son = (JSONArray) object.get("name");
for (int i = 0; i < strJson.length(); ++i) {
JSONObject o = (JSONObject) son.get(i);
System.out.println("name:" + o.getString("name") + "," + "age:"
+ o.getInt("age"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
(2)使用Gson中的JsonReader解析json
String string = "{\"class\":1,\"students\":[{\"name\":\"Lucy\",\"age\":12}, {\"name\":\"Tom\",\"age\":23}, {\"name\":\"Niki\",\"age\":22}, {\"name\":\"Linda\",\"age\":31}]}";
StringReader reader = new StringReader(string);
JsonReader jsonReader = new JsonReader(reader);
try {
jsonReader.beginObject();
if(jsonReader.nextName().equals("class")){
System.out.println("班级:"+jsonReader.nextString());
if(jsonReader.nextName().equals("students")){
jsonReader.beginArray();
while(jsonReader.hasNext()){
jsonReader.beginObject();
if(jsonReader.nextName().equals("name")){
System.out.println("名字:"+jsonReader.nextString());
}
if(jsonReader.nextName().equals("age")){
System.out.println("年龄:"+jsonReader.nextString());
}
jsonReader.endObject();
}
jsonReader.endArray();
}
}
jsonReader.endObject();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}