使用JSON的方法
JSON 即 JavaScript Object Natation,它是一种轻量级的数据交换格式,非常适合于服务器与 JavaScript 的交互。本文将快速讲解 JSON 格式,并通过代码示例演示如何分别在客户端和服务器端进行 JSON 格式数据的处理。
用json和script标签,解决ajax的跨域问题
ajax的XMLHttpRequest因为js的安全问题是不能跨域的
但是<script></script>可以用src="http://otherSite.com/a.js"可以跨域
所以动态写入一个<script></script>就OK了
scr指向一个其它站点的文件,比如:a.jsp?id=15
Json必需的包
commons-httpclient-3.1.jar
commons-lang-2.4.jar
commons-logging-1.1.1.jar
json-lib-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代码转换成json代码
1. List集合转换成json代码
| List list = new ArrayList(); list.add( "first" ); list.add( "second" ); JSONArray jsonArray2 = JSONArray.fromObject( list ); |
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[] { "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 = new boolean[] { true, false, true }; JSONArray jsonArray1 = JSONArray.fromObject(boolArray); |
5. 一般数据转换成json代码
| JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']" ); |
6. beans转换成json代码
| List list = new ArrayList(); JsonBean2 jb1 = new JsonBean2(); jb1.setCol(1); jb1.setRow(1); jb1.setValue("xx"); JsonBean2 jb2 = new JsonBean2(); jb2.setCol(2); jb2.setRow(2); jb2.setValue(""); list.add(jb1); list.add(jb2); JSONArray ja = JSONArray.fromObject(list); |
本文介绍了JSON的基础概念及其在客户端和服务端的应用。通过实例展示了如何使用Java将不同类型的对象(如List、Map、Bean等)转换为JSON格式,以及解决AJAX跨域问题的方法。
10万+

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



