標籤:android json 資料
Android建立JSON格式資料
作為上一篇部落格的補充,簡單那講解了一下Android建立JSON格式資料的小Demo。
1. 建立JSON格式資料
對於Android建立JSON格式資料,由於Android官方提供了相應了put(key, value)等方法,因此代碼十分簡單,如下所示:
JSONObject jsonObject = new JSONObject();JSONArray jsonArray = new JSONArray();JSONObject object_1 = new JSONObject();JSONObject object_2 = new JSONObject();JSONObject object_3 = new JSONObject();try { object_1.put("id", 1); object_1.put("ide", "eclipse"); object_1.put("name", "Java"); object_2.put("id", 2); object_2.put("ide", "XCode"); object_2.put("name", "Swift"); object_3.put("id", 3); object_3.put("ide", "Visual Studio"); object_3.put("name", "C#"); jsonArray.put(object_1); jsonArray.put(object_2); jsonArray.put(object_3); jsonObject.put("languages", jsonArray); jsonObject.put("cat", "it");} catch (JSONException e) { e.printStackTrace();}Log.i("TESTJSON", jsonObject.toString());
最後列印出來的Log日誌資訊為:
{"languages":[{"id":1,"ide":"eclipse","name":"Java"},{"id":2,"ide":"XCode","name":"Swift"},{"id":3,"ide":"Visual Studio","name":"C#"}],"cat":"it"}
Android建立JSON格式資料