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);
相关推荐
装杯让你飞起来啊21 分钟前
Kotlin List / Array 与 for 循环
开发语言·kotlin·list
qq_5895681014 小时前
springbootweb案例,出现访问 http://localhost:8080/list 一直处于浏览器运转阶段
java·网络协议·http·list·springboot
吉吉611 天前
php反序列化基础知识前奏
android·php·反序列化
小则又沐风a1 天前
list模拟实现
java·服务器·list
迷途之人不知返6 天前
List的模拟实现
数据结构·c++·学习·list
AI玫瑰助手6 天前
Python基础:数据类型的转换(int/str/list等互转)
windows·python·list
书源丶6 天前
三十二、Java集合(一)——Collection与List全家桶
java·windows·list
csdn2015_7 天前
Java List 去重
java·windows·list
迷途之人不知返7 天前
List的学习
数据结构·c++·学习·list
苏渡苇7 天前
Redis 核心数据结构(二)——List 与消息队列
数据结构·redis·list·redis发布订阅