- 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响应给客户端。
举例
明天再写代码