JSON是一种轻量级的数据交换格式,非常适合于服务器与 JavaScript 的交互。是移动开发中数据客户端和服务器端数据交互的不二选择; 尤其是现在HTML5的流行,更显着使用Json 完成数据交互的重要性.
在这里, 我将演示一下Java基本数据转换为Json代码
Json必需包
- json-lib-2.3-jdk15.jar
- commons-lang-2.4.jar
- commons-logging-1.0.4.jar
- ezmorph-1.0.6.jar
- commons-collections-3.2.1.jar
- commons-beanutils-1.8.0.jar
如果不想自己下载jar 可以使用这个demo
1.List集合转换成json代码
List<Person> list = new ArrayList<Person>();
list.add(new Person(0,"nagi_ho", 20,"海淀"));
list.add(new Person(1, "eson_ho", 21,"朝阳"));
JSONArray jsonList = JSONArray.fromObject(list);
System.out.println("1.List集合转换成json代码====>" + jsonList.toString());
2.Map集合转换成json代码
Map map = new HashMap();
map.put("name", "json");
map.put("bool", Boolean.TRUE);
map.put("int", new Integer(1));
map.put("arr", new String[] { "btbu", "b" });
map.put("func", "function(i){ return this.arr; }");
JSONObject jsonMap = JSONObject.fromObject(map);
System.out.