当前位置:网站首页>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 :
边栏推荐
- Global and China chemical mechanical polishing abrasive materials market demand outlook and investment scale forecast report 2022 Edition
- Research Report on global and Chinese vaccine market profit forecast and the 14th five year plan development strategy 2022-2028
- Cnpm installation
- Wechat applet simply realizes chat room function
- Detailed explanation of @jsoninclude annotation in Jackson
- [interview with a large factory] meituan had two meetings. Was there a surprise in the end?
- Face++ realizes face detection by flow
- China rehabilitation hospital industry operation benefit analysis and operation situation investigation report 2022
- [short time average zero crossing rate] short time average zero crossing rate of speech signal based on MATLAB [including Matlab source code 1721]
- Wind farm visualization: wind farm data
猜你喜欢
![[kicad image] download and installation](/img/88/cebf8cc55cb8904c91f9096312859a.jpg)
[kicad image] download and installation
The e-book "action guide for large organizations to further promote zero code application platform" was officially released!
![[Suanli network] problems and challenges faced by the development of Suanli network](/img/90/1d537de057113e2b4754e76746f256.jpg)
[Suanli network] problems and challenges faced by the development of Suanli network

Vegetables sklearn - xgboost (2)

3-7sql injection website instance step 3: attack type and attack strategy

Laravel8 fill data
![[speech discrimination] discrimination of speech signals based on MATLAB double threshold method [including Matlab source code 1720]](/img/36/ad86f403b47731670879f01299b416.jpg)
[speech discrimination] discrimination of speech signals based on MATLAB double threshold method [including Matlab source code 1720]

Distributed solar photovoltaic inverter monitoring
![[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

Gb28181 protocol -- timing
随机推荐
Technology Review: Interpretation of cloud native architecture trend in 2022
Guess the size of the number
RM command – remove file or directory
Exercise: completion
C simple operation mongodb
Yunda's cloud based business in Taiwan construction 𞓜 practical school
Data7202 statistical analysis
Optimal Parking
Laravel8 fill data
Rhcsa--- day 6 operation
Cat command – display the file contents on the terminal device
Websocket in the promotion of vegetable farmers
Notes on dashboard & kuboard installation in kubernetes cluster
十大券商公司哪个佣金最低,最安全可靠?有知道的吗
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
D compile time reflection
[Suanli network] problems and challenges faced by the development of Suanli network
Arm instructions and others
Distributed solar photovoltaic inverter monitoring
【LeetCode】40. Combined summation II (2 strokes of wrong questions)