shaoxiaohuan

一、数据封装

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\']" );

二、JAR包简介

      在你的应用中加入引入JSON-lib包,JSON-lib包同时依赖于以下的JAR包:下载地址:http://json-lib.sourceforge.net/

      1.commons-lang.jar

      2.commons-beanutils.jar

      3.commons-collections.jar

      4.commons-logging.jar 

      5.ezmorph.jar

      6.json-lib-2.2.2-jdk15.jar

用法同上

  JSONObject jsonObject = JSONObject.fromObject(message);
  getResponse().getWriter().write(jsonObject.toString());

当把数据转为json后,用如上的方法发送到客户端。前端就可以取得json数据了。

分类:

技术点:

相关文章: