jyau
2017-04-19 23:17
为什么我的输出结果只有一对花括号啊?
因为你的Bean里只有set方法没有get方法 导致无法获取Bean对象中的属性,所以是光一个{},Bean里全部都自动生存下get方法就好.
输出结果是:{}
import org.json.JSONObject;
public class JSONObjectSample {
public static void main(String[] args) {
createJsonByJavaBean();
}
private static void createJsonByJavaBean() {
PersonInfo info = new PersonInfo();
info.setName("John");
info.setSex("male");
info.setAge(22);
info.setStudent(true);
info.setHobbies(new String[] {"hiking", "swimming"});
JSONObject obj = new JSONObject(info);
System.out.println(obj);
}
class PersonInfo {
private String name;
private String sex;
private int age;
private boolean isStudent;
private String[] hobbies;
public void setName(String name) {
this.name = name;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setAge(int age) {
this.age = age;
}
public void setStudent(boolean isStudent) {
this.isStudent = isStudent;
}
public void setHobbies(String[] hobbies) {
this.hobbies = hobbies;
}
}
}
JSON快速入门(Java版)
102048 学习 · 163 问题
相似问题