日期:2014-05-16 浏览次数:20327 次
package lgf.json.jsonrpc; /** * 采用最通常了String相加来创建json对象 */ 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); } }
package lgf.json.jsonrpc; import org.json.JSONArray; import org.json.JSONObject; /** * 采用json工具包生成规范的String类型的json对象 */ public class NewJsonByJsonrpc { public static void main(String[] args) { //json对象 JSONObject jsonObj = new JSONObject(); // 以键-值对的形式存放数据 jsonObj.put("results","2"); // 而外创建两个json对象。可以放到其他对象中 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数组 jsonArr.put(jsoneachObj1); jsonArr.put(jsoneachObj2); jsonObj.put("rows",jsonArr); String jsonData = jsonObj.toString();//把对象转换为String类型就OK了 System.out.println(jsonData); } }