JSONArray转java的list
时间: 2023-11-14 10:09:30 浏览: 76
Json转list
可以使用Gson库将JSONArray转换为Java的List。具体实现代码如下:
```java
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import java.lang.reflect.Type;
import java.util.List;
public class JsonArrayToList {
public static void main(String[] args) {
String jsonArrayStr = "[{\"name\":\"Tom\",\"age\":18},{\"name\":\"Jerry\",\"age\":20}]";
JSONArray jsonArray = new JSONArray(jsonArrayStr);
Gson gson = new Gson();
Type type = new TypeToken<List<Person>>(){}.getType();
List<Person> personList = gson.fromJson(jsonArray.toString(), type);
System.out.println(personList);
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
```
阅读全文