fastjson2将字符串转换为集合

895 阅读1分钟

第一种方式

  1. 创建一个 TypeReference 对象,以便 fastjson2 可以识别您要转换的对象类型
  2. 使用 TypeReference<List<T>>,其中 T 是列表中元素的类型
  3. 使用 JSON.parseObject() 方法将 JSON 字符串转换为 List 对象。

完整代码如下

public static void main(String[] args) {
String jsonStr = "[\"apple\",\"banana\",\"orange\"]";
TypeReference<List<String>> typeRef = new TypeReference<List<String>>() {};
List<String> list = JSON.parseObject(jsonStr, typeRef);
System.out.println(list);
}

第二种方式和上面类似

  1. 创建一个 TypeReference 对象,以便 fastjson2 可以识别您要转换的对象类型
  2. 使用 TypeReference<T>,其中 T 是列表中元素的类型
  3. 使用 JSON.parseArray() 方法将 JSON 字符串转换为 List 对象。

完整代码如下

public static void main(String[] args) {
String jsonStr = "[\"apple\",\"banana\",\"orange\"]";
TypeReference<String> typeRef = new TypeReference<String>() {};
List<String> list = JSON.parseArray(jsonStr, typeRef.getType);
System.out.println(list);
}