How to create a json string in android

Json format is the commonly used for sending and receiving data from through api. Apart from receiving data from api in json format , we can use json string as parameters which we are sending with url for getting data. In this tutorial we will learn how to create a json object in android and how to create a json array in android.

The two classes which is used to create a json string is JSONObject and JSONArray . The first step is to learn how to create a json object and add items into it. The following code will create a json object named person 1 ,and will add some properties to person like name,id,age etc.

JSONObject person1 = new JSONObject();
try {
person1.put("id", "1");
person1.put("person_name", "Sam");
person1.put("age", "24");

} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Next we will see how to create a json array and add the above json object to new json array, For creating a json array use:

JSONArray personarray = new JSONArray();

And for adding one json object to json array use:

personarray.put(person1);

Now Let us see how to create a complete json string “Persons” which consist of json array which contains a list of persons.

//creating json objects to come inside json array
JSONObject person1 = new JSONObject();
JSONObject person2 = new JSONObject();

//creating json array
JSONArray personarray = new JSONArray();

//creating json object to put json array
JSONObject PersonObject = new JSONObject();

try {

    //adding items to first json object
    person1.put("id", "1");
    person1.put("person_name", "Sam");
    person1.put("age", "24");

    //adding items to second json object
    person2.put("id", "2");
    person2.put("person_name", "Bruce");
    person2.put("age", "30");

    //adding json objects to json array
    personarray.put(person1);
    personarray.put(person2);

    //adding json array to json object
    PersonObject.put("Persons", personarray);

} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

//final json string
String JsonData = PersonObject.toString();

System.out.println("jsonString: "+JsonData);

Which will give you the following output in your log window

{
 "Persons":[
 {
 "id":"1",
 "person_name":"Sam",
 "age":"24"
 },
 {
 "id":"2",
 "person_name":"Bruce",
 "age":"30"
 }
 ]
}

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

Your email address will not be published. Required fields are marked *