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);
相关推荐
世人万千丶2 天前
成语接龙小应用 - HarmonyOS ArkUI 开发实战-TextInput与List列表-PC版本
华为·list·harmonyos·鸿蒙·鸿蒙系统
未若君雅裁2 天前
Python 数据容器详解,list、tuple、str、set、dict 到底怎么选
windows·python·list
苦学的罐头2 天前
C# 协变与逆变深度解析:为什么 IEnumerable<T> 能转换,而 List<T> 不行?
开发语言·c#·list
世人万千丶2 天前
家庭记账本小应用 - HarmonyOS ArkUI 开发实战-Tabs与List组件-PC版本
华为·list·harmonyos·鸿蒙
祭曦念3 天前
【共创季稿事节】鸿蒙原生 ArkTS 布局实践:List + onReachStart/End 分页加载完全指南
windows·list·harmonyos
Irissgwe8 天前
C++ STL 详解:list 的介绍使用与模拟实现
开发语言·c++·stl·list
闪电悠米9 天前
黑马点评-Redis 消息队列-02_list_pubsub_limits
java·数据库·ide·redis·缓存·list·intellij-idea
Chase_______9 天前
【Java杂项】Arrays.asList、List.of 和 new ArrayList:集合可变性避坑
java·windows·list
拂拉氏10 天前
【项目分享-知识讲解】 C++标准库 list类的模拟实现
开发语言·c++·list·封装·stl标准库
csdn_aspnet12 天前
C# list集合 多属性排序
c#·list·linq·排序