1. 程式人生 > >常見的java程式碼轉換成json

常見的java程式碼轉換成json


常見的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", newInteger(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']" );