Java中Json的构建
本笔记跟随慕课网的Java中的Json课程学习并笔记之。如有需要,请参阅http://www.imooc.com/learn/523
1. JSONObject构建json数据
JSONObject wangxiaoer = new JSONObject();
Object nullObject = null;
try {
wangxiaoer.put("name", "王小二");
wangxiaoer.put("age", 25.2);
wangxiaoer.put("birthday", "1990-01-02");
wangxiaoer.put("school", "蓝翔");
wangxiaoer.put("major", new String[]{"理发","挖掘机"});
wangxiaoer.put("has_girlfriend",false );
wangxiaoer.put("car",nullObject);
wangxiaoer.put("house",nullObject);
wangxiaoer.put("comment","这是一个注释");
System.out.println(wangxiaoer.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2. 使用Map构建json
Map<String, Object> wangxiaoer = new HashMap<String, Object>();
Object nullObject = null;
wangxiaoer.put("name", "王小二");
wangxiaoer.put("age", 25.2);
wangxiaoer.put("birthday", "1990-01-02");
wangxiaoer.put("school", "蓝翔");
wangxiaoer.put("major", new String[] { "理发", "挖掘机" });
wangxiaoer.put("has_girlfriend", false);
wangxiaoer.put("car", nullObject);
wangxiaoer.put("house", nullObject);
wangxiaoer.put("comment", "这是一个注释");
System.out.println(new JSONObject(wangxiaoer).toString());
3. 使用JavaBean构建对象
private static void createJsonByBean() {
// TODO Auto-generated method stub
Wangxiaoer wangxiaoer = new Wangxiaoer(); //Wangxiaoer是一个JavaBean
wangxiaoer.setName("王小二");
wangxiaoer.setAge(25.2);
wangxiaoer.setBirthday("1990-02-03");
wangxiaoer.setSchool("蓝翔");
wangxiaoer.setMajor(new String[] { "理发", "挖掘机" });
wangxiaoer.setHas_girlfriend(false);
wangxiaoer.setCar(null);
wangxiaoer.setHouse(null);
wangxiaoer.setComment("这是一个注释");
System.out.println(new JSONObject(wangxiaoer));
}