JSON在客户端的使用
JSON 字符串的格式是基于键值对的数据结构,用于表示结构化数据。它遵循严格的语法规则,常用于前后端数据交互。
1. 基本结构
- JSON 数据结构由两种主要元素构成: - 对象(Object):用花括号 {}包围,包含键值对。
- 数组(Array):用方括号 []包围,包含多个值。
 
- 对象(Object):用花括号 
JSON 对象示例:
{ "name": "张三", "age": 25, "isStudent": true }JSON 数组示例:
{ "subjects": ["Math", "Science", "History"] }2. 数据类型
JSON 支持以下几种数据类型:
- 字符串(String):必须用双引号 ""括起来。
- 数字(Number):整数或浮点数,不需要引号。
- 布尔值(Boolean):true或false,不需要引号。
- 数组(Array):方括号 []包围,里面可以是任意类型的数据。
- 对象(Object):花括号 {}包围,里面是键值对。
- 空值(null):表示空值,不需要引号。
示例:
{ "name": "张三", "age": 25, "isStudent": true,"grades": [85, 90, 95], "address": { "city": "北京", "postalCode": "100000" }, 
"graduationYear": null }3. 语法规则
- 双引号:所有的键名(key)和字符串类型的值都必须使用双引号 "",而不能使用单引号'。
- 键值对:每对键和值之间用冒号 :分隔。
- 逗号分隔:多个键值对之间、数组元素之间必须用逗号 ,分隔,但最后一个元素后面不能有逗号。
- 空格:可以在 JSON 字符串中添加空格或缩进以提高可读性,这对 JSON 解析没有影响。
示例:
{ "name": "张三", "age": 25, "isStudent": true, 
"subjects": ["Math", "Science", "History"] }4. 嵌套结构
JSON 支持对象和数组的嵌套,这使得它能够表达复杂的结构。
示例:
{ "name": "张三", "age": 25, 
"dog": { "name": "小花", "age": 3 }, 
"friends": [ { "name": "李四", "age": 24 }, { "name": "王五", "age": 26 } ] 
}在这个例子中,dog 是一个嵌套的对象,而 friends 是一个包含多个对象的数组。
将JSON串转为对象以及把对象转为JSON串的例子
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><script>// 定义一个符合JSON格式的字符串var personStr = '{ "name": "张三", "age": 10, "dog": { "dname": "小花" }, "loveSingers": ["张小明", "王小东", "李小黑"],"friends": [{"fname": "李四"}, {"fname": "张三"}] }';// 通过JSON.parse()可以把一个JSON字符串转换为一个对象var person = JSON.parse(personStr);// console.log(personStr);// console.log(person);console.log(person.name);console.log(person.age);console.log(person.dog.dname);console.log(person.loveSingers[0]);console.log(person.friends[0].fname);// 通过JSON.stringify() 将一个对象转换为JSON串var personStr2 = JSON.stringify(person);</script>
</head>
<body></body>
</html>

JSON在服务器端的使用
1. 将对象转换为 JSON 字符串
这个过程称为 序列化(Serialization),它将 Java 对象转换为 JSON 字符串,以便可以通过 HTTP 传输或者存储到数据库中。
核心步骤:
- 使用 ObjectMapper类,它是 Jackson 提供的一个核心工具类,专门用于处理 JSON 数据。(需要手动导包)详细导包教程:IDEA2020 手动安装jackson (导包通法)_jackson如何引入idea-CSDN博客
下载包的地址:
下载后搜索Jackson https://mvnrepository.com/
https://mvnrepository.com/
- 调用 writeValueAsString(Object)方法,将 Java 对象转换为 JSON 字符串。
public static void ObjectToString() throws JsonProcessingException {// 创建对象Dog dog = new Dog("招财");Person person = new Person("张三", 10, dog);// 将对象转换为 JSON 字符串ObjectMapper objectMapper = new ObjectMapper();String personStr = objectMapper.writeValueAsString(person);// 输出 JSON 字符串System.out.println(personStr);
}
输出:
{"name": "张三","age": 10,"dog": {"name": "招财"}
}
2. 将 JSON 字符串转换为 Java 对象
这个过程称为 反序列化(Deserialization),它将 JSON 字符串转换为 Java 对象,以便在后端进行进一步的业务逻辑处理。
核心步骤:
- 使用 ObjectMapper类。
- 调用 readValue(String, Class<T>)方法,将 JSON 字符串转换为指定类型的 Java 对象。
public static void JsonToEObject() throws JsonProcessingException {// JSON 字符串String personStr = "{\"name\":\"张三\",\"age\":10,\"dog\":{\"name\":\"招财\"}}";// 将 JSON 字符串转换为对象ObjectMapper objectMapper = new ObjectMapper();Person person = objectMapper.readValue(personStr, Person.class);// 输出对象System.out.println(person);
}
调式时的控制台:

3. 总结:如何在服务器端进行 JSON 和对象之间的转换
对象转换为 JSON 字符串(序列化)
- 用途:当你需要将对象通过网络传输或存储为文本(如数据库中)时,通常将 Java 对象转换为 JSON 字符串。
- 步骤: - 创建一个 Java 对象。
- 使用 ObjectMapper.writeValueAsString()方法将对象转换为 JSON 字符串。
 
- 常见场景: - 将后端生成的对象通过 HTTP 响应发送到前端。
- 将对象持久化为 JSON 格式存储。
 
JSON 字符串转换为对象(反序列化)
-  用途:当你从外部接收到 JSON 数据(比如从前端接收到请求数据,或从数据库中读取 JSON 字符串)时,你通常需要将 JSON 字符串转换为 Java 对象进行处理。 
-  步骤: - 获取 JSON 字符串(从 HTTP 请求、数据库等)。
- 使用 ObjectMapper.readValue()方法将 JSON 字符串转换为 Java 对象。
 
-  常见场景: - 从前端接收 JSON 请求体,将其转换为后端的业务对象。
- 从数据库中读取存储的 JSON 数据,将其解析为对象用于处理。
 
JSON和Map/List/Array之间的转换:
1. JSON 和 Map 之间的转换
 
- Map是一种键值对的数据结构,适合与 JSON 对象的格式进行转换,因为 JSON 对象也是键值对的形式。
- 在 Jackson 中,可以轻松地将 JSON 字符串转换为 Map<String, Object>,或者将Map转换为 JSON 字符串。
1.1 将 JSON 转换为 Map
 
使用 ObjectMapper 的 readValue() 方法将 JSON 字符串转换为 Map<String, Object>。
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;public class JsonToMapExample {public static void main(String[] args) throws Exception {String jsonStr = "{\"name\":\"张三\", \"age\":30, \"dog\":{\"name\":\"小花\"}}";// 创建 ObjectMapperObjectMapper objectMapper = new ObjectMapper();// 将 JSON 转换为 MapMap<String, Object> resultMap = objectMapper.readValue(jsonStr, Map.class);// 输出 Map 内容System.out.println(resultMap);}
}
1.2 将 Map 转换为 JSON
 public  static void MapToJson() throws JsonProcessingException {Map data = new HashMap();data.put("a","value");data.put("b","value");ObjectMapper objectMapper = new ObjectMapper();String s = objectMapper.writeValueAsString(data);System.out.println(s);}2. JSON 和 List 之间的转换
 
- List是一种有序的集合,适合与 JSON 数组进行相互转换。
- 在 Jackson 中,List和 JSON 数组之间的转换也是通过ObjectMapper实现的。
2.1 将 JSON 数组转换为 List
 
JSON 数组可以直接转换为 List,可以是 List<String>、List<Integer> 或 List<Map<String, Object>> 等。
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;public class JsonToListExample {public static void main(String[] args) throws Exception {String jsonArrayStr = "[\"张三\", \"李四\", \"王五\"]";// 创建 ObjectMapperObjectMapper objectMapper = new ObjectMapper();// 将 JSON 数组转换为 ListList<String> resultList = objectMapper.readValue(jsonArrayStr, new TypeReference<List<String>>() {});// 输出 List 内容System.out.println(resultList);}
}
2.2 将 List 转换为 JSON 数组
 
使用 writeValueAsString() 方法可以将 List 转换为 JSON 数组。
   public  static void ListToJson() throws JsonProcessingException {
//        List<String> data1 = new ArrayList<String>();
//        data1.add("a");
//        data1.add("b");
//        data1.add("c");
//
//        String [] data2 = {"a","b","c"};Dog dog = new Dog("招财");Person person = new Person("张三",10,dog);List<Person> data = new ArrayList<Person>();data.add(person);ObjectMapper objectMapper = new ObjectMapper();String s = objectMapper.writeValueAsString(data);System.out.println(s);}