要将JSONArray转换为List,可以使用以下方法:
- 使用json库(如Jackson)解析JSONArray并转换为List。
import com.fasterxml.jackson.databind.ObjectMapper; import org.json.JSONArray; JSONArray jsonArray = new JSONArray("[1, 2, 3]"); ObjectMapper objectMapper = new ObjectMapper(); Listlist = objectMapper.readValue(jsonArray.toString(), new TypeReference >() {});
- 手动遍历JSONArray并将其元素添加到List中。
import org.json.JSONArray; JSONArray jsonArray = new JSONArray("[1, 2, 3]"); Listlist = new ArrayList<>(); for (int i = 0; i < jsonArray.length(); i++) { list.add(jsonArray.getInt(i)); }
- 使用Java 8的Stream API将JSONArray转换为List。
import org.json.JSONArray; JSONArray jsonArray = new JSONArray("[1, 2, 3]"); Listlist = IntStream.range(0, jsonArray.length()) .mapToObj(jsonArray::getInt) .collect(Collectors.toList());
这些方法都可以将JSONArray转换为List,你可以根据需要选择适合你的情况的方法。