当前位置:网站首页>Brief introduction and use of JSON
Brief introduction and use of JSON
2022-06-25 06:23:00 【m0_ fifty-one million two hundred and seventy-four thousand fou】
If you are little white , This set of information can help you become a big bull , If you have rich development experience , This set of information can help you break through the bottleneck
2022web Full set of video tutorial front-end architecture H5 vue node Applet video + Information + Code + Interview questions .
Json
One 、 What is? Json
- JSON(JavaScript Object Notation, JS Object tag ) Is a lightweight data exchange format , At present, it is widely used .
- Using programming language independent Text format To store and represent data .
- A simple and clear hierarchy makes JSON Become the ideal data exchange language .
- Easy to read and write , At the same time, it is also easy for machine analysis and generation , And effectively improve the network transmission efficiency .
stay JavaScript In language , Everything is an object . therefore , whatever JavaScript All types of support are available through JSON To express , Like strings 、 Numbers 、 object 、 Array etc. . Look at his requirements and grammar :
- Objects are represented as key value pairs , Data is separated by commas
- Curly braces hold objects
- Square brackets hold arrays
JSON Key value pair It's for keeping JavaScript A way of targeting , and JavaScript The writing method of the object is also similar , key / The key name in the value pair combination is written before and in double quotation marks “” The parcel , Use a colon : Separate , And then it's worth :
json Data instance :
{"name": "QinJiang"}
{"age": "3"}
{"sex": " male "}
Json and JS The object looks like , Easy to confuse , In fact, you can put Json It means JS String representation of object , It uses text to represent a JS Object information , The essence is a string .
contrast :
// This is an object , Note that key names can also be enclosed in quotation marks
var obj = {a: 'Hello', b: 'World'};
// This is a JSON character string , The essence is a string
var json = "{"a": "Hello", "b": "World"}";
In the front end JS It also encapsulates methods that can make json and js Objects can be transformed into each other , If you are interested, you can search by yourself , The following is mainly about Java Yes Json The operation of .
Two 、Java How to convert objects and Json
1、JackSon
1.1、 Preparation for use
SSM project :
You need to manually import dependencies :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
SpringBoot project :
SpringBoot Bring their own JackSon, There is no need to manually introduce dependencies
1.2、 Easy to use
pojo Entity class :
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
public Integer id;
public Integer age;
public String name;
}
controller:
@RequestMapping(path = "/json")
public String json() throws JsonProcessingException {
// Create a jackson Object mapper for , Used to parse data
ObjectMapper mapper = new ObjectMapper();
// Create an object
User user = new User(1, 3, " Summer sail ");
// Resolve our object to json Format
String json = mapper.writeValueAsString(user);
return json;
}
Running results :
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-M8nYiL9i-1643132389412)(C:Users Limulu AppDataRoamingTypora ypora-user-imagesimage-20220126005344019.png)]](/img/fe/eee6e6f3ba0c9020938691f9b8c80a.jpg)
1.3、 Processing date type
Get into ObjectMapper Object mapping class discovery , It returns a sequence for date processing :
public DateFormat getDateFormat() {
return this._serializationConfig.getDateFormat();
}
meanwhile , It also provides a set Method to modify the date format :
public ObjectMapper setDateFormat(DateFormat dateFormat) {
this._deserializationConfig = (DeserializationConfig)this._deserializationConfig.with(dateFormat);
this._serializationConfig = this._serializationConfig.with(dateFormat);
return this;
}
So for operations with dates , We can customize it :
DateFormat Abstract class , We generally use its subclasses SimpleDateFormat To operate , The string operation rules of this subclass are as follows :
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-z9vMEzAW-1643132389415)(C:Users Limulu AppDataRoamingTypora ypora-user-imagesimage-20220126010507932.png)]](/img/18/400d462a3cd403ebc1fb90a0961433.jpg)
Examples are as follows :
pojo Entity class :
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
public Integer id;
public Integer age;
public String name;
public Date date;
}
controller:
@RequestMapping(path = "/json")
public String json() throws JsonProcessingException {
// Create a jackson Object mapper for , Used to parse data
ObjectMapper mapper = new ObjectMapper();
// Create an object
User user = new User(1, 3, " Summer sail ",new Date());
// to ObjectMapper Object to customize the date format
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy year mm month dd Japan ");
mapper.setDateFormat(simpleDateFormat);
// Resolve our object to json Format
String json = mapper.writeValueAsString(user);
return json;
}
Running results :
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-x9jIxNDm-1643132389415)(C:Users Limulu AppDataRoamingTypora ypora-user-imagesimage-20220126010957593.png)]](/img/d9/32823bfb995f94990cc02e5c76b385.jpg)
2、FastJson
fastjson.jar It's a product developed by Ali, which is specially used for Java Developed packages , Easy to implement json Object and the JavaBean Object conversion , Realization JavaBean Object and the json String conversion , Realization json Object and the json String conversion . Realization json There are many ways to convert , The final result is the same . The biggest advantage is high performance .
2.1、 Preparation for use
Whether it's SSM still SpringBoot All need to introduce dependencies :
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
2.2、 Three main operation classes
JSONObject representative json object
- JSONObject Realized Map Interface , guess JSONObject The underlying operation is made up of Map Realized .
- JSONObject Corresponding json object , Through various forms of get() Method can obtain json Data in object , You can also use things like size(),isEmpty() And so on " key : value " The number of pairs and whether the judgment is empty . Its essence is to achieve Map Interface and call methods in the interface .
JSONArray representative json An array of objects
- Inside there is List To complete the operation in the interface .
JSON representative JSONObject and JSONArray The transformation of
- JSON Class source code analysis and use
- Look closely at these methods , Mainly to achieve json object ,json An array of objects ,javabean object ,json Mutual conversion between strings .
2.3、 Easy to use
pojo Entity class :
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
public Integer id;
public Integer age;
public String name;
}
controller:
@RequestMapping(path = "/fjson")
public String testFjson() throws JsonProcessingException, JSONException {
User user1 = new User(1, 1, " Summer sail 1");
User user2 = new User(2, 2, " Summer sail 2");
User user3 = new User(3, 3, " Summer sail 3");
List<User> list = new ArrayList<User>();
list.add(user1);
list.add(user2);
list.add(user3);
String l1 = JSON.toJSONString(list);
String u1 = JSON.toJSONString(user1);
String u2 = JSON.toJSONString(user2);
String u3 = JSON.toJSONString(user3);
return l1;
}
Running results :
边栏推荐
- [golang] leetcode intermediate - Search rotation sort array & search two-dimensional matrix II
- Talk about TCP and UDP
- Research Report on marketing channel analysis and competitive strategy of China's polycarbonate industry 2022
- ctfshow-misc
- Wechat applet authorization login + mobile phone sending verification code +jwt verification interface (laravel8+php)
- Ethernet
- @Detailed explanation of valid annotation usage
- [kicad image] download and installation
- What happens when redis runs out of memory
- Laravel8+ wechat applet generates QR code
猜你喜欢

Location object

50 days countdown! Are you ready for the Landbridge cup provincial tournament?
Websocket in the promotion of vegetable farmers

Rhcsa--- day 6 operation

ctfshow-misc

IQ debugging of Hisilicon platform ISP and image (1)

What is the slice flag bit
![[road of system analyst] collection of wrong questions in the chapters of Applied Mathematics and economic management](/img/62/dab2ac0526795f2040394acd9efdd3.jpg)
[road of system analyst] collection of wrong questions in the chapters of Applied Mathematics and economic management

The elephant turns around and starts the whole body. Ali pushes Maoxiang not only to Jingdong
![[kicad image] download and installation](/img/88/cebf8cc55cb8904c91f9096312859a.jpg)
[kicad image] download and installation
随机推荐
MV command – move or rename files
Go uses channel to control concurrency
Invalid bound statement (not found)
General test point ideas are summarized and shared, which can be directly used in interview and actual software testing
Leetcode sword finger offer question brushing - day 27
Analysis report on demand scale and Supply Prospect of global and Chinese thermal insulation materials market during the 14th Five Year Plan period 2022-2028
Highway
[road of system analyst] collection of wrong questions in the chapters of Applied Mathematics and economic management
Arm instructions and others
【LeetCode】40. Combined summation II (2 strokes of wrong questions)
Gb28181 protocol -- timing
You can't specify target table for update in from clause error in MySQL
Copying DNA
Wireless industrial Internet of things data monitoring terminal
Global and China financial guarantee marketing strategy and channel dynamic construction report 2022
Pre knowledge of asynchronous operation
Netstat command – displays network status
Hands on deep learning (III)
Vscode voice notes to enrich information (Part 1)
What is the IP address