JSON
概述
JavaScript Object Notation
(JavaScript Object Notation,JavaScript对象表示法,读作/ˈdʒeɪsən/)是一种由道格拉斯·克罗克福特构想和设计、轻量级的数据交换语言,该语言以易于让人阅读的文字为基础,用来传输由属性值或者序列性的值组成的数据对象。尽管JSON是JavaScript的一个子集,但JSON是独立于语言的文本格式,并且采用了类似于C语言家族的一些习惯
特点
1、存储和交换文本信息的语法,类似XML
2、轻量级(小、快)
3、可读性强(容易解析)
案例代码
{
"firstName": "John",
"lastName": "Smith",
"sex": "male",
"age": 25,
"married": false,
"address":
{
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber":
[
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
JSON 语法【重点】
JSON 的语法基本上可以视为 JavaScript 语法的一个子集,包括以下内容:
- 数据使用键/值对表示。建议键使用引号引起来!
- 键/值对使用 ,(逗号)分割。
- 使用大括号保存对象,每个名称后面跟着一个 ':'(冒号)
- 使用方括号保存数组,数组值使用 ,(逗号)分割。
案例代码
{
"book": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},
{
"id":"07",
"language": "C++",
"edition": "second"
"author": "E.Balagurusamy"
}]
}
JSON 支持以下两种数据结构:
- 键/值对集合: 这一数据结构由不同的编程语言支持。
- 有序的值列表: 包括数组,列表,向量或序列等等。
数据格式
JSON 值
- 数字(整数或浮点数)
- 字符串(在双引号中)
- 逻辑值(true 或 false)
- 对象(花括号里)
- 数组(中括号里)
- null
数字、字符串、逻辑值
案例代码
{
"name": "buffer",
age: 16,
'gender': true
}
对象
JSON 对象在花括号中书写:
对象可以包含多个键/值对,键值对之间用逗号分隔
案例代码
{
"id":001,
"name":"张三",
"age":18
}
数组
案例代码
{
name : ["张三", '李四', '王五'],
age : ["1", '2', 3],
info : ['帅']
}
对象数组
- 数据使用[]包含
- 在[]都是JSON格式对象
- 每一个对象之间使用逗号隔开,同时最后一个元素不需要逗号
案例代码1
{
person1: [
{
"name": "张三"
},
{
"age": 1
},
{
"gender": true
}
],
person1: [
{
"name": "李四"
},
{
"age": 2
},
{
"gender": true
}
],
person1: [
{
"name": "翠花"
},
{
"age": 3
},
{
"gender": false
}
]
}
案例代码2
{
"person1": [
{
"name": "张三",
"age": 13,
"gender": true
}
],
"person2": [
{
"name": "李四",
"age": 15,
"gender": true
}
],
"person3": [
{
"name": "翠花",
"age": 19,
"gender": false
}
]
}
JSON数据获取
1、json对象.键名
2、json对象["键名"]
3、数组对象[下标] -》 对应数组
案例代码一
var person = {"name":"张三"};
var name = person.name;
alert(name);
案例代码二
var person = {"name":"张三"};
var name = person["name"];
alert(name);
案例代码三
var persons = {"person" : ["张三", 16, false]};
var name = persons.person[0];
alert(name);
案例代码四
var persons = {
"person": [{
"name": "张三"
}, {
"age": 16
}, {
"gender": false
}]
};
var name = persons.person[0]["name"];
var age = persons.person[1].age;
alert(name + age);
案例代码五
var person = {
"name": "玉田",
"age": 21
};
for (var key in person) {
alert(key + ":" + person[key]);
}
案例代码六
var persons = [{
"name": "老七",
"age": 47,
"gender": true
}, {
"name": "永强",
"age": 23,
"gender": true
}, {
"name": "刘英",
"age": 20,
"gender": false
}];
for (var i = 0; i < persons.length; i++) {
var person = persons[i];
for (var key in person) {
alert(key + ":" + person[key]);
}
}
JSON数据验证
JSON解析【重点】
核心操作
JSON对象转Java对象
Java对象转JSON对象
常见解析器
Gson
Jackson【常用】
Fastjson【常用】
Jackson解析
1、导包
jackson-core-2.2.3.jar jackson-annotations-2.2.3.jar jackson-databind-2.2.3.jar
2、创建Jackson核心类对象 ObjectMapper
3、调用相关转换方法实现解析
实体类
public class Person {
private String name;
private int age;
private boolean gender;
// Constructor、Getters and Setters、toString
}
Java对象转JSON字符串
案例代码
public class JacksonTest {
@Test
public void test1() {
// 准备Java对象
Person person = new Person("玉田", 27, true);
// 获取核心类对象ObjectMapper
ObjectMapper mapper = new ObjectMapper();
try {
// 将Java对象转为Json字符串
String jsonString = mapper.writeValueAsString(person);
System.out.println(jsonString);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
集合转JSON字符串
案例代码
@Test
public void test2() {
// 准备Java对象
Person person1 = new Person("玉田", 51, true, new Date());
Person person2 = new Person("永强", 34, true, new Date());
Person person3 = new Person("大脚", 29, false, new Date());
// 声明一个集合并将数据添加到集合中
List<Person> list = new ArrayList<>();
list.add(person1);
list.add(person2);
list.add(person3);
// 获取核心类对象ObjectMapper
ObjectMapper mapper = new ObjectMapper();
try {
// 将集合转为Json字符串
String jsonString = mapper.writeValueAsString(list); // [{"name":"玉田","age":51,"gender":true,"birthday":"2020-12-01 15:46:46"},{"name":"永强","age":34,"gender":true,"birthday":"2020-12-01 15:46:46"},{"name":"大脚","age":29,"gender":false,"birthday":"2020-12-01 15:46:46"}]
System.out.println(jsonString);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
Map转JSON字符串
案例代码
@Test
public void test4() {
// 准备Java对象
Person person1 = new Person("玉田", 51, true, new Date());
Person person2 = new Person("永强", 34, true, new Date());
Person person3 = new Person("大脚", 29, false, new Date());
// 声明一个集合并将数据添加到集合中
Map<String, Person> map = new HashMap<>();
map.put("person1", person1);
map.put("person2", person2);
map.put("person3", person3);
// 获取核心类对象ObjectMapper
ObjectMapper mapper = new ObjectMapper();
try {
// 将Map转为Json字符串
String jsonString = mapper.writeValueAsString(map); // {"person3":{"name":"大脚","age":29,"gender":false,"birthday":"2020-12-01 15:51:02"},"person2":{"name":"永强","age":34,"gender":true,"birthday":"2020-12-01 15:51:02"},"person1":{"name":"玉田","age":51,"gender":true,"birthday":"2020-12-01 15:51:02"}}
System.out.println(jsonString);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
JSON字符串转Java对象【用的不多】
案例代码
@Test
public void test6() {
String jsonString = "{\"name\":\"玉田\", \"age\":21, \"gender\":true}";
ObjectMapper mapper = new ObjectMapper();
try {
Person person = mapper.readValue(jsonString, Person.class);
System.out.println(person); // Person{name='玉田', age=21, gender=true, birthday=null}
} catch (IOException e) {
e.printStackTrace();
}
}
补充:两个注解的使用
// 被此注解修饰的变量不会进行Json格式的转换
@JsonIgnore
// 被此注解修饰的变量会被格式化
@JsonFormat
案例代码一:@JsonIgnore
实体类
public class Person {
private String name;
private int age;
private boolean gender;
@JsonIgnore
private Date birthday;
// Constructor、Getters and Setters、toString
}
测试类
@Test
public void test3() {
// 准备Java对象
Person person = new Person("玉田", 27, true);
person.setBirthday(new Date());
// 获取核心类对象ObjectMapper
ObjectMapper mapper = new ObjectMapper();
try {
// 将Java对象转为Json字符串
String jsonString = mapper.writeValueAsString(person);
System.out.println(jsonString); // {"name":"玉田","age":27,"gender":true}
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
案例代码二:@JsonFormat
实体类
public class Person {
private String name;
private int age;
private boolean gender;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date birthday;
// Constructor、Getters and Setters、toString
}
测试类
@Test
public void test3() {
// 准备Java对象
Person person = new Person("玉田", 27, true);
person.setBirthday(new Date());
// 获取核心类对象ObjectMapper
ObjectMapper mapper = new ObjectMapper();
try {
// 将Java对象转为Json字符串
String jsonString = mapper.writeValueAsString(person);
System.out.println(jsonString); // {"name":"玉田","age":27,"gender":true,"birthday":"2020-12-01 15:37:31"}
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
FastJson 解析
1、导包
fastjson-1.2.47.jar
2、通过JSON核心类调用解析和转换方法
Java对象转为Json字符串
@Test
public void test1() {
// 准备实体类对象
Person person = new Person("玉田", 21, true, new Date());
// Java对象转为Json字符串
String jsonString = JSON.toJSONString(person);
System.out.println(jsonString); // {"age":21,"birthday":1606839584000,"gender":true,"name":"玉田"}
}
集合转为Json字符串
@Test
public void test2() {
// 准备Java对象
Person person1 = new Person("玉田", 51, true, new Date());
Person person2 = new Person("永强", 34, true, new Date());
Person person3 = new Person("大脚", 29, false, new Date());
// 声明一个集合并将数据添加到集合中
List<Person> list = new ArrayList<>();
list.add(person1);
list.add(person2);
list.add(person3);
// Java对象转为Json字符串
String jsonString = JSON.toJSONString(list);
System.out.println(jsonString); // [{"age":51,"birthday":1606840178091,"gender":true,"name":"玉田"},{"age":34,"birthday":1606840178091,"gender":true,"name":"永强"},{"age":29,"birthday":1606840178091,"gender":false,"name":"大脚"}]
}
Json字符串转Java对象
@Test
public void test3() {
// 准备Json字符串
String jsonString = "{\"age\":21,\"birthday\":1606839584000,\"gender\":true,\"name\":\"玉田\"}";
// 将Json字符串解析成实体类对象
Person person = JSON.parseObject(jsonString, Person.class);
System.out.println(person);
}
Json字符串转Json对象
@Test
public void test4() {
// 准备Json字符串
String jsonString = "{\"age\":21,\"birthday\":1606839584000,\"gender\":true,\"name\":\"玉田\"}";
// 将Json字符串转为Json对象
JSONObject jsonObject = JSON.parseObject(jsonString);
System.out.println(jsonObject);
// 根据键获取对应的值
String name = jsonObject.getString("name");
System.out.println(name);
System.out.println(jsonObject.getInteger("age"));
}
Json字符串转Json数组
@Test
public void test5() {
// 准备Json字符串
String jsonString = "[{\"age\":51,\"birthday\":1606840178091,\"gender\":true,\"name\":\"玉田\"},{\"age\":34," +
"\"birthday\":1606840178091,\"gender\":true,\"name\":\"永强\"},{\"age\":29,\"birthday\":1606840178091," +
"\"gender\":false,\"name\":\"大脚\"}]";
// Json字符串转Json数组
JSONArray objects = JSON.parseArray(jsonString);
System.out.println(objects);
// 增强for循环获取所有的Json对象
for (Object object : objects) {
// 强制类型转换
JSONObject jsonObject1 = (JSONObject) object;
// 根据键获取对应的值
System.out.println(jsonObject1.getString("name"));
System.out.println(jsonObject1.getInteger("age"));
}
// 获取Json数组中指定下标位置的java对象
Person person = objects.getObject(2, Person.class);
System.out.println(person);
}
Json数组转集合
@Test
public void test6() {
// 准备Json字符串
String jsonString = "[{\"age\":51,\"birthday\":1606840178091,\"gender\":true,\"name\":\"玉田\"},{\"age\":34," +
"\"birthday\":1606840178091,\"gender\":true,\"name\":\"永强\"},{\"age\":29,\"birthday\":1606840178091," +
"\"gender\":false,\"name\":\"大脚\"}]";
// Json字符串转Json数组
JSONArray objects = JSON.parseArray(jsonString);
// 讲Json数组转为集合
List<Person> list = objects.toJavaList(Person.class);
// 增强for循环拿到所有的对象
for (Person person : list) {
System.out.println(person);
}
}
版权属于:不冷
本文链接:https://www.buleng.xyz/archives/92/
转载时须注明出处及本声明