java工具:《字符串转List》

文章目录

一、介绍

这段代码演示了使用阿里巴巴 Fastjson 库将 JSON 字符串转换为 Java 对象列表的两种常用方式。

方式一:通过 JSONObject.parseObject 结合 TypeReference 实现泛型反序列化。首先创建空的 ArrayList 对象,然后调用 parseObject 方法,传入 JSON 字符串和 TypeReference<List> 类型引用,即可将 JSON 数组转换为指定泛型类型的对象列表。这种方式适用于需要明确指定泛型类型的场景,能够避免类型擦除问题。

方式二:通过 JSONArray.parseArray 直接进行转换。该方法更加简洁,直接传入 JSON 字符串和目标类的 Class 对象,即可快速将 JSON 数组转换为对应类型的列表。这种方式适用于结构简单、类型明确的场景。

两种方式均可实现 JSON 到 Java 列表的转换,方式一通过 TypeReference 保留了泛型信息,方式二则更加简洁直观,开发者可根据实际需求和编码习惯选择使用。

二、代码

java 复制代码
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.JSONObject;

String str = "[
  {
    "id": 5,
    "nodeIdArr": "[\"221\",\"222\"]",
    "nodeNameArr": "[\"enb_221\",\"2222\"]",
    "upperLimitOfTheBusyTimeThreshold": 9,
    "lowerLimitOfTheBusyTimeThreshold": 2,
    "dateRangeBeginTime": 1701648000000,
    "dateRangeEndTime": 1701682200000,
    "createTime": 1701676594000,
    "updateTime": 1701737385000,
    "activeState": "1"
  },
  {
    "id": 6,
    "nodeIdArr": "[\"2003\",\"501\",\"10010\"]",
    "nodeNameArr": "[\"CityA\",\"501\",\"Vir1\"]",
    "upperLimitOfTheBusyTimeThreshold": 9,
    "lowerLimitOfTheBusyTimeThreshold": 2,
    "dateRangeBeginTime": 1701648000000,
    "dateRangeEndTime": 1701682200000,
    "createTime": 1701676641000,
    "updateTime": 1701737382000,
    "activeState": "1"
  }]"
List<BusyTimeIndicatorAlarmThreshold> busyTimeIndicatorAlarmThresholdList = new ArrayList<>();
busyTimeIndicatorAlarmThresholdList = JSONObject.parseObject(str, new TypeReference<List<BusyTimeIndicatorAlarmThreshold>>() {});

方式一

java 复制代码
List busyTimeIndicatorAlarmThresholdList = new ArrayList<>();
busyTimeIndicatorAlarmThresholdList = JSONObject.parseObject(str, new TypeReference<List>() {});

方式二

java 复制代码
List userList = JSONArray.parseArray(str, User.class);
相关推荐
cike_y2 天前
Java反序列化漏洞-Shiro721流程分析
java·反序列化·shiro框架
Severus_black3 天前
C实现双向链表和相关函数!巨详细!
c语言·数据结构·链表·list
Magic--3 天前
C++ STL中vector与list的核心区别
c++·windows·list
li1670902704 天前
第十章:list
c语言·开发语言·数据结构·c++·算法·list·visual studio
游乐码4 天前
C#List
开发语言·c#·list
代码改善世界4 天前
【C++初阶】双向循环链表:List底层结构的完整实现剖析
c++·链表·list
我头发多我先学5 天前
C++ STL list 原理到模拟实现
开发语言·c++·list
‎ദ്ദിᵔ.˛.ᵔ₎6 天前
LIST 的相关知识
数据结构·list
不爱吃炸鸡柳6 天前
C++ STL list 超详细解析:从接口使用到模拟实现
开发语言·c++·list
Access开发易登软件6 天前
在 Access 中实现 Web 风格 To Do List
前端·数据结构·microsoft·list·vba·access·access开发