当前位置:网站首页>JSON数据与List集合之间的正确转换
JSON数据与List集合之间的正确转换
2022-06-28 09:25:00 【自律的西瓜L】
1.JSON数据与List集合之间的正确转换
@Test
public void testJsonObjectCastToList() {
// 0.集合测试数据准备
List<PersonInfo> personInfos = new ArrayList<>();
PersonInfo personInfoOne =
new PersonInfo("小明", 18, 178.89);
PersonInfo personInfoTwo =
new PersonInfo("小红", 18, 165.56);
personInfos.add(personInfoOne);
personInfos.add(personInfoTwo);
// 1.JSON数据与List集合之间的正确转换
// 1.1 将List集合转为JSON数据字符串
String str = JSON.toJSONString(personInfos);
System.out.println(str);
// [{"age":18,"height":178.89,"name":"小明"},{"age":18,"height":165.56,"name":"小红"}]
// 1.2 将JSON数据转为list集合
List<PersonInfo> personInfoList;
try {
personInfoList = JSON.parseArray(str, PersonInfo.class);
} catch (Exception e) {
log.error("JSON解析异常:{}", ExceptionUtils.getStackTrace(e));
personInfoList = new ArrayList<>();
}
System.out.println(personInfoList);
// [PersonInfo(name=小明, age=18, height=178.89), PersonInfo(name=小红, age=18, height=165.56)]
/**
* 2.以下代码执行时,会报异常:
* com.alibaba.fastjson.JSONException: syntax error, expect {,
* actual error, pos 1, fastjson-version 1.2.62
*/
// // 2.1 将集合直接转为字符串
// String strMethod = String.valueOf(personInfos);
// System.out.println(strMethod);
// [PersonInfo(name=小明, age=18, height=178.89), PersonInfo(name=小红, age=18, height=165.56)]
// // 2.2 将JSON数据转为list集合
// List<PersonInfo> personInfoListStr = JSON.parseArray(strMethod, PersonInfo.class);
// System.out.println(personInfoListStr);
}边栏推荐
猜你喜欢

1181:整数奇偶排序

Data mining modeling practice

小米旗下支付公司被罚 12 万,涉违规开立支付账户等:雷军为法定代表人,产品包括 MIUI 钱包 App

1. Kimball dimension modeling of data warehouse: what is a fact table?

redis5.0的槽点迁移,随意玩(单机迁移集群)

Interpretation of new products: realm launched GT neo2 Dragon Ball customized version

Function sub file writing

买卖股票费用计算

基于宽表的数据建模

Dbeaver连接人大金仓KingbaseES V8(超详细图文教程)
随机推荐
Bron filter Course Research Report
股票 停牌
Linux下安装redis 、Windows下安装redis(超详细图文教程)
分而治之之经典Hanoi
异常
JVM系列(2)——垃圾回收
Key summary V of PMP examination - execution process group
Which occupational groups are suitable for the examination
PMP考试重点总结八——监控过程组(2)
DolphinScheduler使用系统时间
1180:分数线划定/P1068 [NOIP2009 普及组] 分数线划定
SQL optimization experience: from 30248 seconds to 0.001 seconds
Regular verification of mobile phone number and email [easy to understand]
PMP考试重点总结五——执行过程组
SQL 优化经历:从 30248秒到 0.001秒的经历
Flip CEP skip policy aftermatchskipstrategy Skippastlastevent() matched no longer matches the Bikeng Guide
PMP needs to master its own learning methods
两道面试小Demo
Two interview demo
A classic JVM class loaded interview question class singleton{static singleton instance = new singleton(); private singleton() {}