
文章目录
一、介绍
这段代码演示了使用阿里巴巴 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);