问答详情
源自:3-3 使用Java Bean构建对象

为什么我的输出结果只有一对花括号啊?

为什么我的输出结果只有一对花括号啊?

提问者:jyau 2017-04-19 23:17

个回答

  • qq_这是只仓鼠_0
    2017-04-21 19:00:06
    已采纳

    因为你的Bean里只有set方法没有get方法 导致无法获取Bean对象中的属性,所以是光一个{},Bean里全部都自动生存下get方法就好.

  • jyau
    2017-04-19 23:18:59

    输出结果是:{}

  • jyau
    2017-04-19 23:18:24

    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;

    }

    }

    }