Java的JSONArray如何通过ArraysasList方法进行转换
JSONArray可以通过Arrays.asList()方法进行转换,具体步骤如下:
- 创建JSONArray对象,例如:
JSONArray jsonArray = new JSONArray();
jsonArray.put("apple");
jsonArray.put("banana");
jsonArray.put("orange");
- 调用Arrays.asList()方法,将JSONArray对象转换成List集合,例如:
List<String> list = Arrays.asList(jsonArray.toString().split(","));
其中,jsonArray.toString()方法将JSONArray对象转换成字符串,再使用split()方法将字符串按照逗号分隔成数组,最后使用Arrays.asList()方法将数组转换成List集合。
注意:
- 转换后的List集合是不可修改的,即不能使用add()、remove()等方法进行操作;
- 如果JSONArray中包含的元素类型不一致,转换时需要进行类型转换。例如,如果JSONArray中既包含字符串又包含数字,可以先将JSONArray转换成字符串类型的List集合,然后使用stream()方法进行类型转换,例如:
List<String> stringList = Arrays.asList(jsonArray.toString().split(","));
List<Integer> integerList = stringList.stream().map(Integer::valueOf).collect(Collectors.toList());
``
原文地址: https://www.cveoy.top/t/topic/d88m 著作权归作者所有。请勿转载和采集!