sjunothing 2016-07-05
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
JSONObject json = new JSONObject();
json.put("id","1");
json.put("name","张三");
json.put("address","陕西西安市");
json.put("sex","男神");
json.put("age","1");
//fromObject将Java对象转换成json字符串,
//toBean将json对象转换成Java对象;
//将json转为为bean
System.out.println("=======将json转为为bean===========");
People people = (People) JSONObject.toBean(json, People.class);
System.out.println(people.getAddress());
//获取json,然后依次添加bean中
System.out.println("=======获取json,然后依次添加bean中===========");
JSONArray jsonArray = JSONArray.fromObject(json);
for(int i=0;i<jsonArray.size(); i++){
JSONObject jsonJ=jsonArray.getJSONObject(i);
jsonJ.getInt("id");
jsonJ.getString("name");
jsonJ.getString("address");
System.out.println(jsonJ.getString("address"));
}
//然后把bean转换为json传给前台
System.out.println("=======然后把bean转换为json传给前台===========");
People p1=new People();
p1.setId("1");
p1.setName("张岱年");
p1.setAddress("1");
p1.setSex("男");
p1.setAge(0);
JSONObject.fromObject(p1).toString();
//JSONArray.fromObject(p1).toString();
System.out.println(JSONObject.fromObject(p1).toString());
System.out.println(JSONArray.fromObject(p1).toString());
System.out.println(JSONSerializer.toJSON(p1).toString());
//转换 List集合到JSON
//如果你是转换List集合,一定得用JSONArray或是JSONSrializer提供的序列化方法。
//如果你用JSONObject.fromObject方法转换List会出现异常,
//通常使用JSONSrializer这个JSON序列化的方法,它会自动识别你传递的对象的类型,然后转换成相应的JSON字符串。
System.out.println("转换 List集合到JSON");
List<People> stu = new ArrayList<People>();
stu.add(p1);
JSONArray.fromObject(p1).toString();
//System.out.println(JSONObject.fromObject(p1).toString());
System.out.println(JSONArray.fromObject(p1).toString());
//将Map集合转换成JSON对象
System.out.println("将Map集合转换成JSON对象");
Map<String, Object> map = new HashMap<String, Object>();
map.put("p", p1);
map.put("int", new Integer(1));
map.put("arr", new String[] { "a", "b" });
map.put("func", "function(i){return this.arr[i]; }");
JSONObject.fromObject(map).toString();
JSONArray.fromObject(map).toString();
JSONSerializer.toJSON(map).toString();
System.out.println(JSONObject.fromObject(map).toString());
System.out.println(JSONArray.fromObject(map).toString());
System.out.println(JSONSerializer.toJSON(map).toString());
//将更多类型转换成JSON
System.out.println("将更多类型转换成JSON");
String[] sa = {"a", "b", "c"};
JSONArray.fromObject(sa).toString();
JSONSerializer.toJSON(sa).toString();
System.out.println(JSONArray.fromObject(sa).toString());
System.out.println(JSONSerializer.toJSON(sa).toString());
}