转自:http://hi.baidu.com/%CF%C2%D2%BB%D5%BEprovence/blog/item/36f04a65a1bed731ab184caa.html
Java代码转换成json代码
1. List集合转换成json代码
List list = new ArrayList(); list.add( "first" ); list.add( "second" ); JSONArray jsonArray2 = JSONArray.fromObject( list )
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);
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());
JSONObject jsonObject = JSONObject.fromObject(new JsonBean());
4. 数组转换成json代码
boolean[] boolArray = new boolean[] { true, false, true };
JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
5. 一般数据转换成json代码
JSONArray jsonArray3 = JSONArray.fromObject( "['json','is','easy']" );
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);
######
下面的链接中也有一些对象或者map、list转换成json的代码:
http://topic.csdn.net/u/20090420/09/1e2c07bd-8618-47ef-aaf7-6e92b26a9aa8.html