實(shí)用jsonrpc-1.0.jar包可以簡單的實(shí)現(xiàn)拼接出json對(duì)象。下面看兩個(gè)對(duì)比的代碼:
1)采用原始的String類型相加實(shí)現(xiàn):
- package lgf.json.jsonrpc;
- /**
- * 采用最通常了String相加來創(chuàng)建json對(duì)象
- */
- public class NewJsonByString {
- public static void main(String[] args) {
- String jsonData = "";
- jsonData = "{" +
- "results:" + "2" + "," +
- "rows:[" +
- "{id: '1', firstname: 'Bill', occupation: 'Gardener' }, " +
- "{id: '2', firstname: 'Ben' , occupation: 'Horticulturalist' }"+
- "]" +
- "}";
- System.out.println(jsonData);
- }
- }
2)采用jsonrpc-1.0的方法同樣實(shí)現(xiàn)
- package lgf.json.jsonrpc;
- import org.json.JSONArray;
- import org.json.JSONObject;
- /**
- * 采用json工具包生成規(guī)范的String類型的json對(duì)象
- */
- public class NewJsonByJsonrpc {
- public static void main(String[] args) {
- //json對(duì)象
- JSONObject jsonObj = new JSONObject();
- // 以鍵-值對(duì)的形式存放數(shù)據(jù)
- jsonObj.put("results","2");
-
- // 而外創(chuàng)建兩個(gè)json對(duì)象。可以放到其他對(duì)象中
- JSONObject jsoneachObj1 = new JSONObject();
- JSONObject jsoneachObj2 = new JSONObject();
- jsoneachObj1.put("id","1");
- jsoneachObj1.put("occupation","Gardener");
- jsoneachObj1.put("firstname","Bill");
-
-
- jsoneachObj2.put("id","2");
- jsoneachObj2.put("firstname","Ben");
- jsoneachObj2.put("occupation","Horticulturalist");
-
- JSONArray jsonArr = new JSONArray(); // json數(shù)組
- jsonArr.put(jsoneachObj1);
- jsonArr.put(jsoneachObj2);
-
- jsonObj.put("rows",jsonArr);
-
- String jsonData = jsonObj.toString();//把對(duì)象轉(zhuǎn)換為String類型就OK了
- System.out.println(jsonData);
- }
- }
|