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']" );
// 普通的数据转化为json格式
public static void test3()
{
String str = "[";
str += "'wy','12'";
str += "]";
System.out.println(str);
JSONArray obj = JSONArray.fromObject(str);
System.out.println(obj);
// {"name":"wy","age":"12"}
}
// 普通的数据转化为json格式
public void test2()
{
String str = "{";
str += "name:[";
str += "'wy','eu','we'";
str += "]";
str += "}";
System.out.println(str);
JSONObject obj = JSONObject.fromObject(str);
System.out.println(obj);
}
// list 格式转化为json
public void test1()
{
List list = new ArrayList();
for(int i = 0; i < 10; i++)
{
list.add("test" + i);
}
System.out.println(list);
JSONArray js = JSONArray.fromObject(list);
System.out.println(js);
}
转载:http://blog.csdn.net/wangyang1354/article/details/49736213