需要先导入json-org.jar
https://pan.baidu.com/s/1-QttGFsENt94MOHE_0doVA 提取码:s1so
定义POJO类(有属性和getter和setter)
package my;
public class Student {
String name;
int id;
String sex;
String phone;
public Student(String Name,int Id,String Sex,String Phone) {
this.name=Name;
this.id=Id;
this.sex=Sex;
this.phone=Phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
POJO转JSON对象
Student student=new Student("王冲", 2016111, "男", "184333");
JSONObject jobj=new JSONObject(student);//必须有getter和setter
String str=jobj.toString(2);//2为缩进宽度
System.out.println(str);
POJO转JSON数组
ArrayList<Student> students=new ArrayList();
students.add(new Student("Tom", 111, "男", "20202011"));
students.add(new Student("Jack", 111, "男", "20202022"));
students.add(new Student("Lisa", 111, "女", "20202033"));
JSONArray jobj=new JSONArray(students);
System.out.println(jobj.toString(2));