使用JSON的方法
JSON即JavaScript Object Natation,它是一种轻量级的数据交换格式,非常适合于服务器与JavaScript的交互。本文将快速讲解JSON格式,并通过代码示例演示如何分别在客户端和服务器端进行JSON格式数据的处理。
Json必需的包
commons-httpclient-3.1.jar
commons-lang-2.4.jar
commons-logging-1.1.1.jar
json-lib-2.2.3-jdk13.jar
ezmorph-1.0.6.jar
commons-collections-3.2.1.jar
以上包可以从
http://commons.apache.org/index.html
http://json-lib.sourceforge.net/
http://ezmorph.sourceforge.net/
中下载到。
出现java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher错误是因为没有导入ezmorph.jar文件或版本不对。
出现java.lang.NoClassDefFoundError: org/apache/commons/collections/map/ListOrderedMap错误是因为没有导入commons-collections.jar文件或版本不对。
Java代码转换成json代码
1.List集合转换成json代码
| List list =newArrayList(); list.add("first"); list.add("second"); JSONArray jsonArray2 = JSONArray.fromObject( list ); |
2.Map集合转换成json代码
| Map map =newHashMap(); map.put("name","json"); map.put("bool", Boolean.TRUE); map.put("int",newInteger(1)); map.put("arr",newString[] {"a","b"}); map.put("func","function(i){ return this.arr[i]; }"); JSONObject json = JSONObject.fromObject(map); |
3.Bean转换成json代码
| JSONObject jsonObject = JSONObject.fromObject(new JsonBean()); |
4.数组转换成json代码
| boolean[] boolArray =newboolean[] {true,false,true}; JSONArray jsonArray1 = JSONArray.fromObject(boolArray); |
5.一般数据转换成json代码
| JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']" ); |
6.beans转换成json代码
| List list =newArrayList(); JsonBean2 jb1 =newJsonBean2(); jb1.setCol(1); jb1.setRow(1); jb1.setValue("xx"); JsonBean2 jb2 =newJsonBean2(); jb2.setCol(2); jb2.setRow(2); jb2.setValue(""); list.add(jb1); list.add(jb2); JSONArray ja = JSONArray.fromObject(list); |

被折叠的 条评论
为什么被折叠?



