当前位置:网站首页>File parsing (JSON parsing)
File parsing (JSON parsing)
2022-07-26 07:56:00 【Why can't I eat mango】
One . What is? JSON
JSON Is a lightweight data exchange format , It's based on ECMAScript A subset of , Use text format completely independent of programming language to store and represent data . A simple and clear hierarchy makes JSDN Become the ideal data exchange language . Easy to read and understand , At the same time, it is also easy for machine analysis and generation , And effectively improve the network transmission efficiency .
Two .JSON grammar
Use braces { } Save the object , Each object consists of several pieces of data
Each data is generated by key : value Key value pairs make up
Use commas between data , Separate
Use \ Escape special characters
{"key1" : value1,"key1" : value1,......"keyN" : valueN}
Use brackets **[ ]** Save array ( aggregate ), Array ( aggregate )… Can contain multiple objects
[{"key1" : value1,"key1" : value1,......"keyN" : valueN},
{"key1" : value1,"key1" : value1,......"keyN" : valueN},
......]
data:[{"key1" : value1,"key1" : value1,......"keyN" : valueN},
{"key1" : value1,"key1" : value1,......"keyN" : valueN},
......]
3、 ... and .JSON Use of
JSON As a lightweight data exchange format , Its main purpose is to transfer data between computer systems , It has the following advantages :
·JSON Only use **UTF-8** code , There is no coding problem ;
·JSON The content only includes **key-value** Key value pair , The format is simple , There is no redundant structure , It is a lightweight structure ;
· Browser built in JSON Support , If you use the data JSON Send it to the browser , It can be used **JavaScript** Deal directly with ;
therefore , Development Web When applied , Use JSON As data transmission , It is very convenient on the browser side .JSON Natural fit JavaScript Handle , therefore , most RESTAPI All choices JSON As a data transfer format .
Four .Java analysis JSON
Use a third-party library to JSON Parsing of file format data
Commonly used for parsing JSON The third-party library of :
·Jackson
·Gson
·Fastjson
Fastjson
Fastjson It's Alibaba's open source JSON Parsing library , It can parse JSON Format string , Support will java The object is serialized into json Formatted data , Can also be json The string of the format is inversely sequenced into Java object .
Fastjson advantage :
Fast
Widely used
The test is complete ( There are many. testcase, Perform regression tests every time you release commas , Ensure the quality is stable )
Easy to use (fastjson Of API It's very simple )
Fully functional ( Supports generics , Support streaming large text , Support enumeration , Support serialization and deserialization extension )
.Fastjson The main object of : The main use of JSON,JSONObject,JSONArray Three categories , among JSONObject and
JSONArray Inherit JSON.
JSON class :
JSON Class is used for original transformation , Common methods are :
take java object **** serialize by json Formatted data :
JSON.toJSONString(Object object);
// Entity data
Weather weather = new Weather();
weather.setCity(" Xi'an ");
weather.setComfort_index(" Very comfortable ");
weather.setDate_y("2022 year 07 month 10 Japan ");
// Convert to json Format string ( serialize )
String json = JSON.toJSONString(weather);
System.out.println(json);
- take json Format String Inverse sequence become Java object
①. JSONObject class :
It is mainly used for packaging key-value Key value pair data , It inherited LinkedHashMap Interface .
**** JSON.parseObject()****
// json Format data
String jsonStr = "{\"temperature\":\"29℃~41℃\",\"weather\":\" It's cloudy \",\"weather_id\":{\"fa\":\"01\",\"fb\":\"02\"},\"wind\":\" The Northeast breeze \",\"week\":\" Sunday \",\"city\":\" Xi'an \",\"date_y\":\"2022 year 07 month 10 Japan \",\"dressing_index\":\" scorching hot \",\"dressing_advice\":\" It's hot , Suggest a short shirt 、 Short skirt 、 shorts 、 Thin type T Cool summer clothes such as T-shirts .\",\"uv_index\":\" secondary \",\"comfort_index\":\"\",\"wash_index\":\" More appropriate \",\"travel_index\":\" Less suitable \",\"exercise_index\":\" Less suitable \",\"drying_index\":\"\"}";
// convert to JSONObject
JSONObject jsonObj = JSON.parseObject(jsonStr);
System.out.println(" date :" + jsonObj.getString("date_y"));
System.out.println(" City :" + jsonObj.getString("city"));
System.out.println(" The weather :" + jsonObj.getString("weather"));
System.out.println(" temperature :" + jsonObj.getString("temperature"));
②. JSONArray class :
JSONArray Class is mainly used to encapsulate the data of array collection class , It is inherited from ArrayList class
JSON.parseArray()
// json Format data
String jsonStr = "{\r\n" +
"\r\n" +
" \"title\": \" Shanghai municipal police station information \",\r\n" +
" \"list\": [{\r\n" +
" \"name\": \" Hudong University police station of cultural relics protection branch \",\r\n" +
" \"addr\": \" Zhongshan North 1st Road 801 Number \",\r\n" +
" \"tel\": \"22027732\"\r\n" +
" }, {\r\n" +
" \"name\": \" Huxi University police station of cultural relics protection branch \",\r\n" +
" \"addr\": \" Furongjiang road 55 Number \",\r\n" +
" \"tel\": \"62751704\"\r\n" +
" }, {\r\n" +
" \"name\": \" Wusong water police station of water Public Security Bureau \",\r\n" +
" \"addr\": \" Songpu Road 187 Number \",\r\n" +
" \"tel\": \"56671442\"\r\n" +
" }, {\r\n" +
" \"name\": \" Yangpu water police station of water Public Security Bureau \",\r\n" +
" \"addr\": \" Yangshupu Road 1291 Number \",\r\n" +
" \"tel\": \"65898004\"\r\n" +
" }, {\r\n" +
" \"name\": \" Waitan water police station of water Public Security Bureau \",\r\n" +
" \"addr\": \" Zhongshan 2nd Road 8 get 3 Number \",\r\n" +
" \"tel\": \"63305388\"\r\n" +
" }]\r\n" +
"}";
// convert to JSONArray
JSONArray jsonArray = JSON.parseArray(jsonStr);
// Traverse JSONArray
for(int i =0 ; i <jsonArray.size(); i++) {
JSONObject item = jsonArray.getJSONObject(i);
System.out.println(item);
}
Four . common problem
Question 1 :
FastJson Default filter null value , No display null Value fields .
Map<String, Object> map = new HashMap<String, Object>(){
{
put("age", 18);
put("name", " Zhang San ");
put("sex", null);
}
};
System.out.println(JSONObject.toJSONString(map));
【 Running results 】:
【 solve 】:
convert to JSON When the string , Use Feature Enumeration values .
Map<String, Object> map = new HashMap<String, Object>(){
{
put("age", 18);
put("name", " Zhang San ");
put("sex", null);
}
};
// Use Feature Set the enumeration value of type
System.out.println(JSONObject.toJSONString(map,Feature.WriteMapNullValue));
Question two : control JSON Field order of
// Entity class
public class PoliceStation {
private String name;
private String addr;
private String tel;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
// Test class
PoliceStation ps = new PoliceStation();
ps.setName(" Electronic City police station ");
ps.setAddr(" Wangwang planet ");
ps.setTel("14587091409");
System.out.println(JSON.toJSONString(ps));
【 Running results 】:
【 solve 】: The output result is inconsistent with the field definition order . When defining entity class fields , Use @JSONFiled Annotated ordinal Property for sequential configuration .
import com.alibaba.fastjson2.annotation.JSONField;
public class PoliceStation {
@JSONField(ordinal = 1)
private String name;
@JSONField(ordinal = 2)
private String addr;
@JSONField(ordinal = 3)
private String tel;
}
Question 3 :
control JSON Of Date Field format
// Entity order class
public class Order{
// The order no.
private String orderId;
// Date of creation
private LocalDateTime creationTime;
public Order() {
this.orderId = UUID.randomUUID().toString();
this.creationTime = LocalDateTime.now();
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public LocalDateTime getCreationTime() {
return creationTime;
}
public void setCreationTime(LocalDateTime creationTime) {
this.creationTime = creationTime;
}
}
// Test class
public class Test {
public static void main(String[] args) {
Order order1 = new Order();
String json = JSON.toJSONString(order1);
System.out.println(json);
}
}
【 Running results 】
【 solve 】
When outputting the date field , When the default format does not meet the requirements , You can define entity classes in Date Field , Use @JSONFiled Annotated format Property to configure the format .
// Order class
public class Order{
// The order no.
private String orderId;
// Date of creation
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime creationTime;
}
边栏推荐
- Como automatic test system: build process record
- VScode无法启动问题解决思路
- Database foundation
- Dynamic performance view overview
- Basic knowledge of convolutional neural network
- 在线问题反馈模块实战(十四):实现在线答疑功能
- A tutorial for mastering MySQL database audit characteristics, implementation scheme and audit plug-in deployment
- JMeter性能测试之使用CSV文件参数化
- The difference between ArrayList and LinkedList
- DADNN: Multi-Scene CTR Prediction via Domain-Aware Deep Neural Network
猜你喜欢

元宇宙基础设施:WEB 3.0 chain33 优势分析

Hcip--- BGP comprehensive experiment

Use js to count the number of occurrences of each string in the string array, and format it into an object array.

Devaxpress.xtraeditors.datanavigator usage

一文掌握mysql数据库审计特点、实现方案及审计插件部署教程

Simulation of transfer function step response output of botu PLC first-order lag system (SCL)

《门锁》引爆独居安全热议 全新海报画面令人窒息

Regression analysis code implementation

Wrong Addition

QT listview add controls and pictures
随机推荐
Hcip--- BGP comprehensive experiment
Use js to count the number of occurrences of each string in the string array, and format it into an object array.
JMeter performance test saves the results of each interface request to a file
总结软件测试岗的那些常见高频面试题
以太网交换安全
PyTorch
Next item recommendations in short sessions
《门锁》引爆独居安全热议 全新海报画面令人窒息
From boosting to lamdamart
ARIMA model for time series analysis and prediction
What are the differences between FileInputStream and bufferedinputstream?
微服务feign调用时候,token丢失问题解决方案
DCN (deep cross network) Trilogy
Sort sort IP addresses
System architecture & microservices
Yaml language-01 (data type, array, object)
AQS implementation principle
2022.7.22DAY612
The analysis, solution and development of the problem of router dropping frequently
Solution to the problem of token loss when microservice feign is called