- Json(JavaScript Object Notation)是一種輕量級的數據交換格式。
- 它基於JavaScript的一個子集,利用了JavaScript的一些模式來表示結構化數據。
- 它是一種數據格式,而並非編程語言。
- Json並不從屬於JavaScript。
- 很多編程語言都有針對Json的解析器。
Json語法
Json語法是JavaScript對象表示語法的子集
數據在名稱/值對中
數據由逗號分隔
大括號保存對象
中括號保存數組
Json 名稱/值對
“name”: “我是bamzhy”
Json值
數字(整數或浮點數)
字符串(在雙引號中)
邏輯值(true 或 false)
數組(在中括號中)
對象(在大括號中)
null
{“age”: 18}
Json 對象
Json對象在大括號中{}書寫:
對象可以包含多個名稱/值對
var haha={name: "bamzhy", aim: "成爲合格的Java工程師"}
key 和 value 中使用冒號(:)分割。
每個 key/value 對使用逗號(,)分割。
key必須是字符串,value 可以是合 法的 JSON 數據類型(字符串, 數字, 對象, 數組, 布爾值或 null)
如何打印出Json數據呢?使用alert();
alert(haha.name)
Json數組
Json數組在中括號中書寫
數組可包含多個對象
{
"sites":[
{"name": "taobao", "url": "www.taobao.com"};
{"name": "baidu", "url": "www.baidu.com"};
{"name": "google", "url": "www.google.com"}
]
}
Json布爾值/null
Json布爾值可以是true或者false,可以設置null值
{“flag”:true}
{“flag”:null}
tips
- Json對象和Json字符串的區別:
Json對象
Json字符串
var str1={"name": "taobao", "url": "www.taobao.com"};
var str2='{"name": "taobao", "url": "www.taobao.com"}'
一個綜合例子
- 這兩段代碼表達的意思是一樣的。
class Person{
int id;
String name;
Info info;
Info[] infos;
}
class Info{
String add;
String hobby;
}
System.out.println(Person.id);
System.out.println(Person.name);
System.out.println(Person.info.add);
System.out.println(Person.info.hobby);
System.out.println(Person.infos[0].add);
System.out.println(Person.infos[1].hobby);
var person={name:"zhangsan" ,age:18,
info:{add:"shenzhen",hobby:"eat"},
infos:[{add:"shenzhen",hobby:"eat"}]}
alert(person.name);
alert(person.age;
alert(person.info.add);
alert(person.info.hobby);
alert(person.infos[0].add);
alert(person.infos[1].hobby);
Spring MVC 支持Json
導包
@RequestBody註解
RequestBody註解用於讀取http請求的內容,通過SpringMVC提供的HttpMessageConverter接口將讀到的內容轉換爲json、xml等格式的數據並綁定到Controller類方法的參數上
@ResponseBody註解
ResponseBody註解用於將Controller類的方法返回的對象,通過HttpMessageConverter接口轉換爲指定格式的數據如:json、xml等,通過Response響應給客戶端。
舉例
明天再寫代碼