当前位置:网站首页>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;
}
边栏推荐
- Selenium: detailed explanation of browser crawler use (I)
- Leetcode sword finger offer special (I) integer
- HOT100 hash
- Program environment and pretreatment
- Stack simulation queue
- Brief description of hystrix configuration
- Model pruning 3: learning structured sparsity in deep neural networks
- Read and write of zip file
- Copy pcap file with producer consumer model
- Anaconda 中安装 百度飞浆Paddle 深度学习框架 教程
猜你喜欢

Matlab-二/三维图上绘制黑点

Lnmp+wordpress to quickly build a personal website

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

Database foundation

Kdd2022 | uncover the mystery of Kwai short video recommendation re ranking, and recommend the new SOTA

Wrong Addition

MySQL implementation plan

记一次路由器频繁掉线问题的分析、解决与发展

Use of JMeter performance test to store response content to file listener

Jmeter性能测试之将每次接口请求的结果保存到文件中
随机推荐
Tensorflow learning diary tflearn
2022.7.22DAY612
Summary of API method
Using producer consumer model and dpkt to process pcap files
Database foundation
【每日一题】919. 完全二叉树插入器
2022.7.22DAY612
Use of JMeter performance test to store response content to file listener
Logical volume management (LVM)
Introduction to C language (8)
Simulation of transfer function step response output of botu PLC first-order lag system (SCL)
Jmeter性能测试之将每次接口请求的结果保存到文件中
API (common class 2)
Rack server expansion memory
C language keyword extern
Come across the sea to see you
Basic knowledge of convolutional neural network
Regular expression rules and common regular expressions
Wrong Addition
Sort: merge sort and quick sort