最近用到JSON,查阅整理了一下。有点长。。。不割
1.JSON介绍
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。(官方网站http://www.json.org)
2.JSON语法
JSON 语法是 JavaScript 语法的子集。
JSON语法的规则就是:使用大括号' { } ',中括号' [ ] ',逗号' ,',冒号' :',双引号' “ ” '。
JSON 值可以是:数字(整数或浮点数)、字符串(在双引号中)、逻辑值(true 或 false)、数组(在方括号中)、对象(在花括号中)、null 。
JSON 数据的书写格式是:名称 / 值对。
名称/值对组合中的名称写在前面(在双引号中),值对写在后面(同样在双引号中),中间用冒号隔开:
"firstName":"John"
这很容易理解,等价于这条 JavaScript 语句:
firstName="John"
3.JSON基础结构
4.JSON具体形式
例子:表示人的一个对象:
{
"姓名":"大憨",
"年龄":24
}
{
"学生":
[
{"姓名":"小明","年龄":23},
{"姓名":"大憨","年龄":24}
]
}
5.JSON基础示例
名称 / 值对
{"firstName":"Brett"}
这个示例非常基本,而且实际上比等效的纯文本"名称 / 值对"占用更多的空间:
firstName=Brett
{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"}
表示数组
{
"people":[
{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"},
{"firstName":"Jason","lastName":"Hunter","email":"bbbb"},
{"firstName":"Elliotte","lastName":"Harold","email":"cccc"}
]
}
这不难理解。在这个示例中,只有一个名为 people的变量,值是包含三个条目的数组,每个条目是一个人的记录,其中包含名、姓和电子邮件地址。上面的示例演示如何用括号将记录组合成一个值。当然,可以使用相同的语法表示多个值(每个值包含多个记录):
{"programmers":[
{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"},
{"firstName":"Jason","lastName":"Hunter","email":"bbbb"},
{"firstName":"Elliotte","lastName":"Harold","email":"cccc"}
],
"authors":[
{"firstName":"Isaac","lastName":"Asimov","genre":"sciencefiction"},
{"firstName":"Tad","lastName":"Williams","genre":"fantasy"},
{"firstName":"Frank","lastName":"Peretti","genre":"christianfiction"}
],
"musicians":[
{"firstName":"Eric","lastName":"Clapton","instrument":"guitar"},
{"firstName":"Sergei","lastName":"Rachmaninoff","instrument":"piano"}
]}
6.JSON格式应用
赋值给变量
var people={"programmers":[{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"},
{"firstName":"Jason","lastName":"Hunter","email":"bbbb"},
{"firstName":"Elliotte","lastName":"Harold","email":"cccc"}
],
"authors":[ {"firstName":"Isaac","lastName":"Asimov","genre":"sciencefiction"},
{"firstName":"Tad","lastName":"Williams","genre":"fantasy"},
{"firstName":"Frank","lastName":"Peretti","genre":"christianfiction"}
],
"musicians":[ {"firstName":"Eric","lastName":"Clapton","instrument":"guitar"},
{"firstName":"Sergei","lastName":"Rachmaninoff","instrument":"piano"}
]}
访问数据
尽管看起来不明显,但是上面的长字符串实际上只是一个数组;将这个数组放进 JavaScript变量之后,就可以很轻松地访问它。实际上,只需用点号表示法来表示数组元素。所以,要想访问 programmers 列表的第一个条目的姓氏,只需在 JavaScript 中使用下面这样的代码:people.programmers[0].lastName;
people.authors[1].genre//Valueis"fantasy"
people.musicians[3].lastName//Undefined.Thisreferstothefourthentry,andthereisn'tone
people.programmers[2].firstName//Valueis"Elliotte"
修改数据
正如可以用点号和方括号访问数据,也可以按照同样的方式轻松地修改数据:people.musicians[1].lastName="Rachmaninov";
换回字符串
7.实例比较
XML和JSON都使用结构化方法来标记数据,下面来做一个简单的比较。
用XML表示中国部分省市数据如下:
<?xmlversion="1.0"encoding="utf-8"?>
<country>
<name>中国</name>
<province>
<name>黑龙江</name>
<cities>
<city>哈尔滨</city>
<city>大庆</city>
</cities>
</province>
<province>
<name>广东</name>
<cities>
<city>广州</city>
<city>深圳</city>
<city>珠海</city>
</cities>
</province>
<province>
<name>台湾</name>
<cities>
<city>台北</city>
<city>高雄</city>
</cities>
</province>
<province>
<name>新疆</name>
<cities>
<city>乌鲁木齐</city>
</cities>
</province>
</country>
用JSON表示如下:
{
"name": "中国",
"province": [
{
"name": "黑龙江",
"cities": {
"city": ["哈尔滨","大庆"]
}
},
{
"name": "广东",
"cities": {
"city": ["广州","深圳","珠海"]
}
},
{
"name": "台湾",
"cities": {
"city": ["台北","高雄"]
}
},
{
"name": "新疆",
"cities": {
"city": ["乌鲁木齐"]
}
}
]
}
编码的可读性,xml有明显的优势,毕竟人类的语言更贴近这样的说明结构。json读起来更像一个数据块,读起来就比较费解了。不过,我们读起来费解的语言,恰恰是适合机器阅读,所以通过json的索引.province[0].name就能够读取“黑龙江”这个值。
编码的手写难度来说,xml还是舒服一些,好读当然就好写。不过写出来的字符JSON就明显少很多。去掉空白制表以及换行的话,JSON就是密密麻麻的有用数据,而xml却包含很多重复的标记字符。
跟XML相比,JSON简洁明了,操作方便,JSON和XML都是基于文本的,两者都使用Unicode编码。JSON和XML都很容易阅读。主观上,JSON更清晰,冗余更少。XML适合标记文档(配置文件),JSON更适合数据交换。
8.JSON操作
1、JSON字符串转换成JAVAScript对象(调用eval())
JSON本来就是JS的一个子集,所以可以使用JS的解释器
<script>
var my_json='{"FBI":[{"name":"rose","age":"25"},{"name":"jack","age":"25"}],"NBA":[{"name":"tom","sex":"man"},{"name":"jack","sex":"women"}]}';
var my_object=eval('('+my_json+')');
document.writeln(my_object.FBI[1].name);
</script>
上面的代码也可省略属性的双引号
var my_json='{FBI:[{name:"rose",age:"25"},{name:"jack",age:"25"}],NBA:[{name:"tom",sex:"man"},{name:"jack",sex:"women"}]}';
2、将JS对象转换成JSON字符串(调用toJSONString())
需要下载json.js(http://www.json.org/json.js)
<script src="json.js"></script>
<script>
var my_object={
FBI:[
{name:"rose",age:"25"},
{name:"jack",age:"25"}
],
NBA:[
{name:"tom",sex:"man"},
{name:"jack",sex:"women"}
]
};
document.writeln(my_object.toJSONString());
</script>
3、XML与JSON转换
(需要下载json.org提供的JAVA类,json.zip[http://www.json.org/java/json.zip])
package away;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import org.json.JSONObject;
import org.json.XML;
public class XMl2JSON {
public static void main(String[] args) {
BufferedReader buffRed=null;
BufferedWriter buffWri=null;
try{
//将XML转换成JSON
String fileName1="away.xml";
buffRed=new BufferedReader(new FileReader(fileName1));
String tempStr;
StringBuffer xmlStrBuff=new StringBuffer();
while((tempStr=buffRed.readLine())!=null)
xmlStrBuff.append(tempStr);
System.out.println("JSON str="+XML.toJSONObject(xmlStrBuff.toString()));
//将JSON转换成XML
String jsonStr="{Heros:{FBI:[{name:\"rose\",age:\"25\"},{name:\"jack\",age:\"25\"}],NBA:[{name:\"tom\",sex:\"man\"},{name:\"jack\",sex:\"women\"}]}};";
String fileName2="myxml.xml";
buffWri=new BufferedWriter(new FileWriter(fileName2));
JSONObject jsonObj=new JSONObject(jsonStr);
buffWri.write("<?xml version=\"1.0\" encoding=\"GBK\"?>");
buffWri.newLine();
buffWri.write("<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">");
buffWri.newLine();
buffWri.write(XML.toString(jsonObj));
buffWri.flush();
System.out.println("run end!");
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(buffRed!=null)
buffRed.close();
if(buffWri!=null)
buffWri.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
xml文件内容:
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="no">away</entry>
<entry key="name">HELLO_AWAY</entry>
</properties>
输出结果:
JSON str={"properties":{"entry":[{"key":"no","content":"away"},{"key":"name","content":"HELLO_AWAY"}]}}
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<Heros><NBA><sex>man</sex><name>tom</name></NBA><NBA><sex>women</sex><name>jack</name></NBA><FBI><age>25</age><name>rose</name></FBI><FBI><age>25</age><name>jack</name></FBI></Heros>
4、AJAX中运用JSON
(比使用DOM解析XML简单)//在响应的程序中输入返回的值:
out.println("{FBI:[{name:\"rose\",age:\"25\"},{name:\"jack\",age:\"25\"}],NBA:[{name:\"tom\",sex:\"man\"},{name:\"jack\",sex:\"women\"}]}");
//在页面上(点确定页面上会显示jack)
<script language="javascript" src="js/prototype.js"></script>
<input type="button" οnclick="loadInfo()" value="确定"/>
<script>
function loadInfo(){
new Ajax.Request("hello",{
onComplete:function(req){
var res=eval("("+req.responseText+")");
$('mydiv').innerHTML=res.FBI[1].name;
}
}
);
}
</script>
<div id="mydiv"></div>
5、Java中运用Json
(需要下载json的java开发包)package callCenterServer;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
ArrayList<Area> areas=new ArrayList<Area>();
areas.add(new Test.Area("福建","福州"));
areas.add(new Test.Area("福建","厦门"));
areas.add(new Test.Area("福建","泉州"));
areas.add(new Test.Area("四川","成都"));
areas.add(new Test.Area("四川","攀枝花"));
JSONObject jsonObject=new JSONObject();
for(Test.Area area:areas){
if(jsonObject.has(area.province)){
JSONArray jsonArray=(JSONArray)jsonObject.get(area.province);
jsonArray.put(area.city);
}else{
JSONArray jsonArray=new JSONArray();
jsonArray.put(area.city);
jsonObject.put(area.province, jsonArray);
}
}
System.out.println(jsonObject);
}
static class Area{
private final String province;
private final String city;
Area(String province,String city){
this.province=province;
this.city=city;
}
}
}
输出:{"四川":["成都","攀枝花"],"福建":["福州","厦门","泉州"]}
9.小结
(1)JSON的数据结构只有两种;
(2)可以嵌套表示,比如Array中可以嵌套Object等;
(3)记住:Object是以{}表示,Array是以[ ]表示;
-整理:Chay-
欢迎交流 http://blog.csdn.net/ycwol/article/details/39369867
correct 正确
{
"id":1,
"name":"chay",
...
}
{
"correct":[
{
"id":1,
"name":"chay"
},
...
],
...
}
error 错误
{
"request" : "/statuses/home_timeline.json",
"error_code" : "20502",
"error" : "Need you follow uid."
}