帮我写一个Demo实现JSONArray类型转为Java实体类
时间: 2023-05-15 08:07:22 浏览: 120
将Json对象转化为Java实体类
5星 · 资源好评率100%
好的,可以的。以下是一个简单的示例代码:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class JSONArrayToJavaEntityDemo {
public static void main(String[] args) {
String jsonArrayStr = "[{\"id\":1,\"name\":\"张三\",\"age\":20},{\"id\":2,\"name\":\"李四\",\"age\":25}]";
try {
JSONArray jsonArray = new JSONArray(jsonArrayStr);
List<Person> personList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Person person = new Person();
person.setId(jsonObject.getInt("id"));
person.setName(jsonObject.getString("name"));
person.setAge(jsonObject.getInt("age"));
personList.add(person);
}
System.out.println(personList);
} catch (JSONException e) {
e.printStackTrace();
}
}
static class Person {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
}
希望这个示例可以帮到你!
阅读全文