Showing posts with label JSON Object. Show all posts
Showing posts with label JSON Object. Show all posts

Friday, August 8, 2014

Create JSON Array and JSON Object




private String writeJSON() {

             JSONObject student1Detail = new JSONObject();
             try {
                    student1Detail.put("id", "1");
                    student1Detail.put("name", "abc");
             } catch (JSONException e) {
                    e.printStackTrace();
             }

             JSONObject student2Detail = new JSONObject();
             try {
                    student2Detail.put("id", "2");
                    student2Detail.put("name", "xyz");
             } catch (JSONException e) {
                    e.printStackTrace();
             }

             JSONArray jsonArray = new JSONArray();

             jsonArray.put(student1Detail);
             jsonArray.put(student2Detail);

             JSONObject studentsObj = new JSONObject();
             try {
                    studentsObj.put("Students", jsonArray);
             } catch (JSONException e) {
                    e.printStackTrace();
             }

             String jsonStr = studentsObj.toString();
             System.out.println("jsonString: " + jsonStr);

             return jsonStr;
       }


Output :

{"Students":[{"id":"1","name":"abc"},{"id":"2","name":"xyz"}]}