首页 > 代码库 > FastJson

FastJson

FastJson的应用

将javaBean对象包装成json格式

                JSONObject jsonObject=new JSONObject();        User user=new User("尚晓飞", "男", 25, new Date(), "bjsxt");        jsonObject.put("user", user);        System.out.println("Test.main()"+jsonObject.toString());                //打印结果:Test.main(){"user":{"age":25,"birthDay":1405067572140,"name":"尚晓飞","school":"bjsxt","sex":"男"}}
View Code

将list集合包装成json

 1 User user=new User("尚晓飞", "男", 25, new Date(), "bjsxt"); 2         User user2=new User("sxf", "女", 22, new Date(), "北京尚学堂"); 3         User user3=new User("当当", "男", 25, new Date(), "当当网"); 4         List<Object> userList=new ArrayList<Object>(); 5          6         userList.add(user); 7         userList.add(user2); 8         userList.add(user3); 9         10         JSONObject jsonObject=new JSONObject();11         jsonObject.put("userlist", userList);12         13         14         System.out.println("Test.main()"+jsonObject);15         16 //打印结果:Test.main(){"userlist":[{"age":25,"birthDay":1405069939080,"name":"尚晓飞","school":"bjsxt","sex":"男"},{"age":22,"birthDay":1405069939080,"name":"sxf","school":"北京尚学堂","sex":"女"},{"age":25,"birthDay":1405069939080,"name":"当当","school":"当当网","sex":"男"}]}
View Code

将list集合包装成json格式的数组

 1 User user=new User("尚晓飞", "男", 25, new Date(), "bjsxt"); 2         User user2=new User("sxf", "女", 22, new Date(), "北京尚学堂"); 3         User user3=new User("当当", "男", 25, new Date(), "当当网"); 4         List<Object> userList=new ArrayList<Object>(); 5          6         userList.add(user); 7         userList.add(user2); 8         userList.add(user3); 9         10         JSONArray jsonArray=new JSONArray(userList);11         12         13         System.out.println("Test.main()"+jsonArray);14 15 //打印结果:Test.main()[{"age":25,"birthDay":1405069524031,"name":"尚晓飞","school":"bjsxt","sex":"男"},{"age":22,"birthDay":1405069524031,"name":"sxf","school":"北京尚学堂","sex":"女"},{"age":25,"birthDay":1405069524031,"name":"当当","school":"当当网","sex":"男"}]
View Code

将list集合包装成json格式的数组

1 User user=new User("尚晓飞", "男", 25, new Date(), "bjsxt");2         User user2=new User("sxf", "女", 22, new Date(), "北京尚学堂");3         User user3=new User("当当", "男", 25, new Date(), "当当网");4         List<Object> userList=new ArrayList<Object>();5         6         userList.add(user);7         userList.add(user2);8         userList.add(user3);9         JSON json=(JSON) JSON.toJSON(userList);
View Code

 

 在javascript中操作json对象

 1 //如果是一个json对象var abc={"key":"value"} 2 //取出key对应的值 3 var v=abc.key 4 var v=abc["key"] 5  6  7 //如果是一个json数组的对象   var abc=[{"one":"一","name":"尚晓飞"},{"one":"二","name":"尚小帅"}] 8  9 for(var i=0;i<abc.length;i++){10      var m=abc[i].name;11      var o=abc[i].one; 12      var m=abc[i]["name"]           13 }
View Code