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);
相关推荐
三8449 小时前
PHP Session 反序列化(2):漏洞根因 —— 序列化处理器错位与对象注入
android·web安全·php·反序列化·session
charlie1145141911 天前
浅谈C++的列表初始化std::initializer_list
开发语言·数据结构·c++·list·开源项目
努力的lpp1 天前
php反序列化一(大白话版)
开发语言·web安全·php·ctf·反序列化
小刘在重生~3 天前
Java 集合|Collection、List、ArrayList、LinkedList、泛型、Collections 工具类
java·数据结构·list
暖焰核心5 天前
迭代器与模板的结合——stl的list
c++·windows·list
.YM.Z7 天前
C++ STL 容器深度剖析:vector 与 list 的模拟实现及对比
开发语言·c++·vector·list
重生之小比特7 天前
【初阶C++】list
开发语言·c++·list
2301_800074217 天前
map,list简单方法
windows·python·list
xxwxx__8 天前
C++ list 深度解析:从使用原理到模拟实现
开发语言·c++·list
鹿角片ljp8 天前
LeetCode 56:合并区间复盘|从排序思维到 List<int[]> 的简洁写法
算法·leetcode·list