当前位置:网站首页>Fastjson parses JSON strings (deserialized to list, map)
Fastjson parses JSON strings (deserialized to list, map)
2022-07-06 21:16:00 【I hope to wake up naturally every day】
List of articles
When dealing with database in daily development , Often with Json Format string stored in the database , When in Java Get the corresponding Json Format String After the string , How to convert to the data format we want ( Like converting to Java Custom classes in ), You need to make the right Json Data analysis , The interface I recently wrote meets such a demand , I use Ali's Fastjson api Realization json Turn into Java POJO, Now let's make a simple summary , Make a note of .
To configure maven rely on
Introduce three dependencies respectively , Namely fastjson、lombok、commons tool kit .
<dependencies>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
</dependencies>
I have written the version number , Please use a specific version if necessary , It is recommended to use the latest version of .
Data preparation
Let's simply construct a little data , Requirements for data analysis : Whole json Turn into a POJO, among code、name The type is String,schedule The type is List<String> Represents the plan list ,completion The type is Map<String,String> It means that the completion is mapped one by one .
Build Monday to Sunday plan & completion Of json data :
[
{
"code":"monday",
"name":" Monday ",
"schedule":"get_up_9am,exercise_one_hour,study_one_hour,goto_bed_before_12pm",
"completion":"get_up_9am=y,exercise_one_hour=n,study_one_hour=y,goto_bed_before_12pm=n"
},{
"code":"tuesday",
"name":" Tuesday ",
"schedule":"exercise_one_hour,study_one_hour,goto_bed_before_12pm",
"completion":"exercise_one_hour=y,study_one_hour=y,goto_bed_before_12pm=y"
},{
"code":"wednesday",
"name":" Wednesday ",
"schedule":"get_up_9am,exercise_one_hour,goto_bed_before_12pm",
"completion":"get_up_9am=n,exercise_one_hour=n,goto_bed_before_12pm=n"
},{
"code":"thursday",
"name":" Thursday ",
"schedule":"",
"completion":""
},{
"code":"friday",
"name":" Friday ",
"schedule":"study_one_hour,goto_bed_before_12pm",
"completion":"study_one_hour=n,goto_bed_before_12pm=n"
},{
"code":"saturday",
"name":" Saturday ",
"schedule":"goto_bed_before_12pm",
"completion":"goto_bed_before_12pm=n"
},{
"code":"sunday",
"name":" Sunday ",
"schedule":"",
"completion":""
}
]
JSON Format string to Java object
The following is the direct post code
DO&DTO
DO It's all for String Data of type ,DTO It's one of them schedule by List,completion by Map Format
WeekScheduleDO
package com.xxx;
import lombok.Data;
@Data
public class WeekScheduleDO {
private String code;
private String name;
private String schedule;
private String completion;
}
WeekScheduleDTO
package com.fast;
import lombok.Data;
import java.util.List;
import java.util.Map;
@Data
public class WeekScheduleDTO {
private String code;
private String name;
private List<String> schedule;
private Map<String,String> completion;
}
SelfJSONUtils
Customize and encapsulate the methods needed for parsing
package com.xxx;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
import java.util.stream.Collectors;
public class SelfJSONUtils {
public static List<WeekScheduleDTO> toWeekScheduleDOs(String str){
// String->List<WeekScheduleDO>
List<WeekScheduleDO> weekScheduleDOs = JSON.parseObject(str, new TypeReference<List<WeekScheduleDO>>() {
});
List<WeekScheduleDTO> result = new ArrayList<>();
for (WeekScheduleDO item:weekScheduleDOs) {
result.add(toWeekScheduleDTO(item));
}
return result;
}
private static WeekScheduleDTO toWeekScheduleDTO(WeekScheduleDO item){
WeekScheduleDTO weekScheduleDTO = new WeekScheduleDTO();
weekScheduleDTO.setCode(item.getCode());
weekScheduleDTO.setName(item.getName());
// "schedule":"get_up_9am,..." convert to lsit
String[] schedule = item.getSchedule().split(",");
weekScheduleDTO.setSchedule(Arrays.stream(schedule).filter(e -> StringUtils.isNoneBlank(e)).collect(Collectors.toList()));
// "completion":"get_up_9am=y,..." convert to map
weekScheduleDTO.setCompletion(toMap(item.getCompletion().split(",")));
return weekScheduleDTO;
}
private static Map<String,String> toMap(String[] args){
Map<String,String> map = new HashMap<>();
for(String arg : args){
if(!arg.isEmpty()) {
String[] split1 = arg.split("=");
map.put(split1[0], split1[1]);
}
}
return map;
}
}
test & call
package com.xxx;
import java.util.List;
public class Demo {
public static void main(String[] args) {
String json = "[{\"code\":\"monday\",\"name\":\" Monday \",\"schedule\":\"get_up_9am,exercise_one_hour,study_one_hour,goto_bed_before_12pm\",\"completion\":\"get_up_9am=y,exercise_one_hour=n,study_one_hour=y,goto_bed_before_12pm=n\"},{\"code\":\"tuesday\",\"name\":\" Tuesday \",\"schedule\":\"exercise_one_hour,study_one_hour,goto_bed_before_12pm\",\"completion\":\"exercise_one_hour=y,study_one_hour=y,goto_bed_before_12pm=y\"},{\"code\":\"wednesday\",\"name\":\" Wednesday \",\"schedule\":\"get_up_9am,exercise_one_hour,goto_bed_before_12pm\",\"completion\":\"get_up_9am=n,exercise_one_hour=n,goto_bed_before_12pm=n\"},{\"code\":\"thursday\",\"name\":\" Thursday \",\"schedule\":\"\",\"completion\":\"\"},{\"code\":\"friday\",\"name\":\" Friday \",\"schedule\":\"study_one_hour,goto_bed_before_12pm\",\"completion\":\"study_one_hour=n,goto_bed_before_12pm=n\"},{\"code\":\"saturday\",\"name\":\" Saturday \",\"schedule\":\"goto_bed_before_12pm\",\"completion\":\"goto_bed_before_12pm=n\"},{\"code\":\"sunday\",\"name\":\" Sunday \",\"schedule\":\"\",\"completion\":\"\"}]";
List<WeekScheduleDTO> weekScheduleDTOS = SelfJSONUtils.toWeekScheduleDOs(json);
System.out.println(weekScheduleDTOS);
}
}
Now you can run directly or debug View the resolution

This requirement should be considered as a conventional complex situation , If there are more complicated situations , The transformation form can also be adjusted according to the gourd and the gourd ~
Points of attention
If you're careful , You will find that there is a redundant operation in my code , It is located in SelfJSONUtils#toBatchItemDTO Converted to List Over there Stream Flow place :
weekScheduleDTO.setSchedule(Arrays.stream(schedule).filter(e -> StringUtils.isNoneBlank(e)).collect(Collectors.toList()));
fastjson When you switch , The default is null We're going to get rid of the data ( Optional ), According to this characteristic , I just use the following code ( No, filter):
weekScheduleDTO.setSchedule(Arrays.stream(schedule).collect(Collectors.toList()));
Not really filter(e -> StringUtils.isNoneBlank(e)) You can't . In the code map When you switch , It's really the elimination of empty data , turn map After coming out, I did size=0( Here's the picture ), In turn List When , If there is no empty data , The data will be in "" The form is stored in List in ( I've been in this hole for a long time !!)

Except for the above StringUtils#isNoneBlank Except empty , You can also use e.hashCode()!=0 To solve , Of course, this is not StringUtils Strategies to use when available
weekScheduleDTO.setSchedule(Arrays.stream(schedule).filter(e -> e.hashCode()!=0).collect(Collectors.toList()));
Simply analyze the reasons for this situation :
fastjosn analysis josn by POJO When , First we'll create a pojo An empty object , Then, through the entity class set Method to assign a value to a parameter , because fastjson When parsing, it defaults to null The data of is eliminated , therefore fastjson If the field is not reserved, it will not be set operation , and pojo Class is not assigned by anyone from beginning to end , As String The default type is "", And in the conversion to List When , It will be directly stored in a ""(List<String> Can store multiple "").
This problem may not be big , But when business needs cannot be implemented according to our ideas because of this small point , It's hard to find this tiny problem .
in addition ,JSON The data is deserialized to Java Object time , Must have a default parameterless constructor , Otherwise, the following exceptions will be reported
com.alibaba.fastjson.JSONException: default constructor not found.
Fastjson API
Fastjson Be recognized as Java And json The fastest interactive Library ! Take a brief look at Fastjson Of api Design , For serialization and serialization json There are many optional operations for data , such as @JSONField 、BeanToArray、ContextValueFilter To configure JSON transformation 、NameFilter and SerializeConfig wait . For specific use, please refer to the official API that will do .
Reference resources :
边栏推荐
- The difference between break and continue in the for loop -- break completely end the loop & continue terminate this loop
- OAI 5g nr+usrp b210 installation and construction
- @GetMapping、@PostMapping 和 @RequestMapping详细区别附实战代码(全)
- ##无yum源安装spug监控
- Spiral square PTA
- 【深度学习】PyTorch 1.12发布,正式支持苹果M1芯片GPU加速,修复众多Bug
- KDD 2022 | realize unified conversational recommendation through knowledge enhanced prompt learning
- R language visualizes the relationship between more than two classification (category) variables, uses mosaic function in VCD package to create mosaic plots, and visualizes the relationship between tw
- document.write()的用法-写入文本——修改样式、位置控制
- 字符串的使用方法之startwith()-以XX开头、endsWith()-以XX结尾、trim()-删除两端空格
猜你喜欢

Common English vocabulary that every programmer must master (recommended Collection)
![[interpretation of the paper] machine learning technology for Cataract Classification / classification](/img/0c/b76e59f092c1b534736132faa76de5.png)
[interpretation of the paper] machine learning technology for Cataract Classification / classification

Swagger UI tutorial API document artifact

面试官:Redis中有序集合的内部实现方式是什么?

SAP UI5 框架的 manifest.json

Is it profitable to host an Olympic Games?

爱可可AI前沿推介(7.6)

Introduction to the use of SAP Fiori application index tool and SAP Fiori tools

HMS Core 机器学习服务打造同传翻译新“声”态,AI让国际交流更顺畅

全网最全的新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀
随机推荐
039. (2.8) thoughts in the ward
拼多多败诉,砍价始终差0.9%一案宣判;微信内测同一手机号可注册两个账号功能;2022年度菲尔兹奖公布|极客头条
Regular expression collection
【力扣刷题】一维动态规划记录(53零钱兑换、300最长递增子序列、53最大子数组和)
JS operation DOM element (I) -- six ways to obtain DOM nodes
Why do job hopping take more than promotion?
愛可可AI前沿推介(7.6)
[redis design and implementation] part I: summary of redis data structure and objects
Le langage r visualise les relations entre plus de deux variables de classification (catégories), crée des plots Mosaiques en utilisant la fonction Mosaic dans le paquet VCD, et visualise les relation
Hardware development notes (10): basic process of hardware development, making a USB to RS232 module (9): create ch340g/max232 package library sop-16 and associate principle primitive devices
Reference frame generation based on deep learning
全网最全的新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀
js 根据汉字首字母排序(省份排序) 或 根据英文首字母排序——za排序 & az排序
Study notes of grain Mall - phase I: Project Introduction
Aike AI frontier promotion (7.6)
字符串的使用方法之startwith()-以XX开头、endsWith()-以XX结尾、trim()-删除两端空格
新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀
The biggest pain point of traffic management - the resource utilization rate cannot go up
2022菲尔兹奖揭晓!首位韩裔许埈珥上榜,四位80后得奖,乌克兰女数学家成史上唯二获奖女性
b站视频链接快速获取