当前位置:网站首页>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 :
边栏推荐
- Technology Review: Interpretation of cloud native architecture trend in 2022
- Report on strategic suggestions on investment direction and Prospect of global and Chinese marine biological industry (2022 Edition)
- Global and Chinese medical protective clothing market supply and demand research and investment value proposal report 2022-2028
- Day21 performance test process
- Tencent and China Mobile continued to buy back with large sums of money, and the leading Hong Kong stocks "led" the market to rebound?
- C switch nested syntax
- After five years of software testing in ByteDance, I was dismissed in December to remind my brother of paddling
- Handling skills of SQL optimization (2)
- RT thread i/o device model and layering
- Day22 send request and parameterization using JMeter
猜你喜欢

VMware virtual machine prompt: the virtual device ide1:0 cannot be connected because there is no corresponding device on the host.
![[open source sharing] deeply study KVM, CEPH, fuse features, including open source projects, code cases, articles, videos, architecture brain maps, etc](/img/9d/9bcf52f521e92cf97eb1d545931c68.jpg)
[open source sharing] deeply study KVM, CEPH, fuse features, including open source projects, code cases, articles, videos, architecture brain maps, etc

50 days countdown! Are you ready for the Landbridge cup provincial tournament?

Guess the size of the number

What happens when redis runs out of memory

Digitalization, transformation?
![[hand torn STL] Stack & queue](/img/db/d05c52f8e3fb0aade51460e86cf623.jpg)
[hand torn STL] Stack & queue

Add the author watermark plugin v1.4 update to the posts of elegant grass discuz plugin - some forums post errors and bugs have been fixed
[kicad image] download and installation
[golang] leetcode intermediate - Search rotation sort array & search two-dimensional matrix II
随机推荐
D compile time reflection
Observation configuring wmic
Data7202 statistical analysis
Research Report on marketing channel analysis and competitive strategy of China's polycarbonate industry 2022
RM command – remove file or directory
3-7sql injection website instance step 3: attack type and attack strategy
Vegetables sklearn - xgboost (2)
Explain @builder usage
Interview experience - list of questions
MySQL tuning -- 02 -- slow query log
Research Report on brand strategic management and marketing trends in the global and Chinese preserved fruit market 2022
Research Report on investment share and application prospect of 1,3-propanediol (PDO) industry in the world and China 2022
Analysis report on production and sales demand and sales prospect of global and Chinese phosphating solution Market 2022-2028
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
Talk about TCP and UDP
Distributed solar photovoltaic inverter monitoring
How to use asemi FET 7n80 and how to use 7n80
Notes on dashboard & kuboard installation in kubernetes cluster
Understanding the dynamic mode of mongodb document
Laravel8+ wechat applet generates QR code