当前位置:网站首页>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 :
边栏推荐
- China rehabilitation hospital industry operation benefit analysis and operation situation investigation report 2022
- [network security] sharing of experience and ideas of an emergency battle
- Processes and threads - concepts and process scheduling
- Monitoring access: how to grant minimum WMI access to the monitoring service account
- [speech discrimination] discrimination of speech signals based on MATLAB double threshold method [including Matlab source code 1720]
- [data visualization application] draw spatial map (with R language code)
- Exercise: completion
- What is the slice flag bit
- RT thread i/o device model and layering
- Ethernet
猜你喜欢

No one reads the series. Source code analysis of copyonwritearraylist

What is the slice flag bit
Go quiz: considerations for function naming return value from the go interview question (more than 80% of people answered wrong)
![[v2.0] automatic update system based on motion step API (support disconnection reconnection and data compensation)](/img/73/2ec957d58616d692e571a70826787f.jpg)
[v2.0] automatic update system based on motion step API (support disconnection reconnection and data compensation)

Wechat applet authorization login + mobile phone sending verification code +jwt verification interface (laravel8+php)

Distributed solar photovoltaic inverter monitoring

After five years of software testing in ByteDance, I was dismissed in December to remind my brother of paddling
Websocket in the promotion of vegetable farmers

Methods for obtaining some information of equipment

【LeetCode】40. Combined summation II (2 strokes of wrong questions)
随机推荐
Summary of 6 common methods of visual deep learning model architecture
JS implementation mouse can achieve the effect of left and right scrolling
Tencent and China Mobile continued to buy back with large sums of money, and the leading Hong Kong stocks "led" the market to rebound?
Explain @builder usage
Tablespace free space
Global and Chinese benzoic acid market competition strategy and demand scale forecast report 2022
Arm instructions and others
Handling skills of SQL optimization (2)
Data7202 statistical analysis
Gavin's insight on transformer live class - line by line analysis and field experiment analysis of insurance BOT microservice code of insurance industry in the actual combat of Rasa dialogue robot pro
Research Report on global and Chinese vaccine market profit forecast and the 14th five year plan development strategy 2022-2028
[road of system analyst] collection of wrong questions in the chapters of Applied Mathematics and economic management
Websocket in the promotion of vegetable farmers
Rational investment and internationalism
Highway
Hands on deep learning (III)
TFTP command – uploading and downloading files
Curl command – file transfer tool
What is the slice flag bit
十大券商公司哪个佣金最低,最安全可靠?有知道的吗