写一段用java将json数据转成list的程序
时间: 2024-05-20 22:17:02 浏览: 67
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class JsonToListExample {
public static void main(String[] args) {
String jsonString = "[{\"name\":\"John\",\"age\":30,\"city\":\"New York\"},{\"name\":\"Mary\",\"age\":25,\"city\":\"Los Angeles\"}]";
List<Person> personList = new ArrayList<>();
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
String city = jsonObject.getString("city");
Person person = new Person(name, age, city);
personList.add(person);
}
System.out.println(personList);
}
static class Person {
String name;
int age;
String city;
public Person(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", city='" + city + '\'' +
'}';
}
}
}
输出结果:
[Person{name='John', age=30, city='New York'}, Person{name='Mary', age=25, city='Los Angeles'}]
阅读全文