JSONArray转对象集合
要将JSONArray转换为对象集合,可以使用以下代码示例:
JSONArray jsonArray = new JSONArray("[{\"name\":\"John\",\"age\":30},{\"name\":\"Jane\",\"age\":25}]");
List<Person> personList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
Person person = new Person(name, age);
personList.add(person);
}
在上面的示例中,我们首先创建了一个JSONArray对象,其中包含了两个JSONObject对象。然后,我们创建了一个空的Person对象集合。
接下来,我们使用for循环遍历JSONArray中的每个JSONObject对象。对于每个JSONObject对象,我们从中获取name和age属性的值,并使用这些值创建一个新的Person对象。最后,将Person对象添加到personList中。
请注意,这里的Person是一个自定义的类,其构造函数接受name和age参数。你可以根据自己的需求更改代码中的类和属性名称
原文地址: http://www.cveoy.top/t/topic/h91z 著作权归作者所有。请勿转载和采集!