当前位置:网站首页>JSON notes
JSON notes
2022-07-28 06:58:00 【wr_01】
One 、 summary
Concept :JavaScript Object Notation.JavaScript Object notation .
The following is JavaScript Object definition format :
{
name:"zhangsan",
age:23,
city:" Beijing "
}
Let's take a look at JSON The format of :
{
"name":"zhangsan",
"age":23,
"city":" Beijing "
}
Pass above js Object format and json Compare the format , Two formats are found to be particularly similar to .
It's just js Attribute names in objects can be quoted ( It can be a single quotation mark , Or double quotes ); and
jsonThe key in the format must be enclosed in double quotation marks , This is ajsonThe rules of the form .
json What is the use of formatted data ?
effect : Because of its simple syntax format , Distinct hierarchy , Now it is mostly used as Data carriers , Data transmission in the network . As shown in the figure below, it is the data that the server responds to the browser , This data is relatively simple , If you need it now JAVA If the data encapsulated in the object responds back to the browser , What kind of data transmission should be used ?

You remember ajax The concept of ? yes Asynchronous JavaScript and xml. there xml This is the way of data transmission in the past , as follows :
<student>
<name> Zhang San </name>
<age>23</age>
<city> Beijing </city>
</student>
Look again json Describe how the above data is written :
{
"name":" Zhang San ",
"age":23,
"city":" Beijing "
}
After comparing the above two formats, you will find json Simple format of data , And less bytes .
Two 、JSON Basic grammar
2.1 Define format
JSON The essence is a string , However, the string content has certain format requirements . The definition format is as follows :
var Variable name = '{"key":value,"key":value,...}';
JSON The key of the string must be enclosed in double quotation marks , The value depends on the type to represent .value The data types of are as follows
- Numbers ( Integer or floating point number )
- character string ( Use double quotes )
- Boolean value (true perhaps false)
- Array ( In square brackets )
- object ( In curly brackets )
- null
Example :
var jsonStr = '{"name":"zhangsan","age":23,"addr":[" Beijing "," Shanghai "," Xi'an "]}'
2.2 Code demonstration
Create a page , On this page <script> Defined in label json character string
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script> //1. Definition JSON character string var jsonStr = '{"name":"zhangsan","age":23,"addr":[" Beijing "," Shanghai "," Xi'an "]}' alert(jsonStr); </script>
</body>
</html>
Open via browser , The page effect is shown in the figure below

Now we need to get the JSON In a string name Property value , What should I do ?
If it is a js object , We can go through js object . Property name To get the data .JS Provides an object JSON , This object has the following two methods :
parse(str): take JSON String to js object . The way to use it is :var jsObject = JSON.parse(jsonStr);stringify(obj): take js Object to JSON strand . The way to use it is :var jsonStr = JSON.stringify(jsObject)
Code demonstration :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script> //1. Definition JSON character string var jsonStr = '{"name":"zhangsan","age":23,"addr":[" Beijing "," Shanghai "," Xi'an "]}' alert(jsonStr); //2. take JSON String to JS object let jsObject = JSON.parse(jsonStr); alert(jsObject) alert(jsObject.name) //3. take JS Object to JSON character string let jsonStr2 = JSON.stringify(jsObject); alert(jsonStr2) </script>
</body>
</html>
2.3 Send asynchronous request with parameters
We use axios When sending a request , If you want to carry complex data, you will use JSON Format , as follows
axios({
method:"post",
url:"http://localhost:8080/ajax-demo/axiosServlet",
data:"username=zhangsan"
}).then(function (resp) {
alert(resp.data);
})
It is impossible for us to splice strings by ourselves for request parameters ? Definitely not , You can define a in advance js object , Used to encapsulate the parameters to be submitted , And then use JSON.stringify(js object ) Convert to JSON strand , And then JSON String as axios Of data Attribute value to submit the request parameters . as follows :
var jsObject = {
name:" Zhang San "};
axios({
method:"post",
url:"http://localhost:8080/ajax-demo/axiosServlet",
data: JSON.stringify(jsObject)
}).then(function (resp) {
alert(resp.data);
})
and axios It's a very powerful tool . We just need to encapsulate the parameters to be submitted into js object , And put the js Object as axios Of data Property value , It will automatically js Object to JSON Submit in series . as follows :
var jsObject = {
name:" Zhang San "};
axios({
method:"post",
url:"http://localhost:8080/ajax-demo/axiosServlet",
data:jsObject // here axios Will be the js Object to json List of
}).then(function (resp) {
alert(resp.data);
})
Be careful :
- js Provided
JSONWe just need to know the object . becauseaxiosWill automatically js Objects andJSONString for want to change conversion .- When sending an asynchronous request , If the request parameter is
JSONFormat , The way of request must bePOST. becauseJSONThe string needs to be placed in the request body .
3、 ... and 、JSON String sum Java The transformation of objects
After learning json after , Let's talk about json The role of . In the future, we will json Format data for front-end and back-end interaction . When the front end sends a request , If it is complex data, it will be in the form of json Submit to the back end ; If the back-end needs to respond to some complex data , It also needs to be json Format the data response back to the browser .

On the back end, we need to focus on the following two parts of operation :
- Request data :JSON String to Java object
- The response data :Java Object to JSON character string
Four 、Fastjson
4.1 Fastjson summary
Fastjson It's one provided by Alibaba Java High performance and perfect function of language JSON library , Is currently the Java The fastest in the language JSON library , Can achieve Java Objects and JSON The mutual conversion of strings .
4.2 Fastjson Use
Fastjson The use is also relatively simple , It is divided into the following three steps to complete
Import coordinates
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency>Java Object turn JSON
String jsonStr = JSON.toJSONString(obj);take Java Object to JSON strand , Just use
FastjsonProvidedJSONClasstoJSONString()Static method .JSON String rotation Java object
User user = JSON.parseObject(jsonStr, User.class);take json Convert to Java object , Just use
FastjsonProvidedJSONClassparseObject()Static method .
4.3 Code demonstration
Introduce coordinates
Create a class , Designed to test Java Objects and JSON Mutual conversion of strings , The code is as follows :
public class FastJsonDemo { public static void main(String[] args) { //1. take Java Object to JSON character string User user = new User(); user.setId(1); user.setUsername("zhangsan"); user.setPassword("123"); String jsonString = JSON.toJSONString(user); System.out.println(jsonString);//{"id":1,"password":"123","username":"zhangsan"} //2. take JSON String to Java object User u = JSON.parseObject("{\"id\":1,\"password\":\"123\",\"username\":\"zhangsan\"}", User.class); System.out.println(u); } }
边栏推荐
- shell脚本——“三剑客”之awk命令
- DHCP principle and configuration
- JS reverse question 100 - question 1
- Centos7 deploy MySQL database server
- What kind of air conduction Bluetooth headset with good configuration is recommended
- Archery database audit platform deployment
- Tcp/ip five layer model
- How to simulate the implementation of strcpy library functions
- Technology sharing | how to do Assertion Verification in interface automated testing?
- Hdu-2036-reform spring breeze blowing all over the ground (polygon area template)
猜你喜欢
随机推荐
技术分享 | 接口测试价值与体系
Vmware workstation configuration net mode
DNS域名解析服务
Network - data link layer
防火墙——iptables防火墙(四表五链、防火墙配置方法、匹配规则详解)
什么是线性表?
HDU-2036-改革春风吹满地(多边形面积模板)
KVM热迁移
网络——传输层(详细版)
Gerapy use
Hdu-5783 divide the sequence (greedy water question)
Pku-2739-sum of constructive prime numbers
Network - transport layer (detailed version)
1、 PXE overview and installation
LNMP搭建过程详解
MySQL主从
Compilation and preprocessing of C language
Array to linked list
Applets: WSX scripts
How about air conduction Bluetooth headset? It's the most worthwhile air conduction headset to start with









