3 Nov 2014

Create json string | JSON format data in android

Today i am going to "How JSON format data in android"

- JSON is very light weight, structured, easy to parse and much human readable.
- JSON is best alternative to XML when your android app needs to interchange data with your server.

Writing JSON is very simple. Just create the JSONObject or JSONArray and use the toString() method.

OUTPUT SCREEN :


FORMAT OUTPUT : 


- Here  is the implementation for creating json string format data :


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity
{
       TextView tvDisplayResult;

       @Override
       protected void onCreate(Bundle savedInstanceState)
       {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
             
              tvDisplayResult=(TextView) findViewById(R.id.tvDisplayResult);
              tvDisplayResult.setText(toJSon());
             
              Log.i("Json String ::", toJSon());

       }

       public static String toJSon()
       {
              try
              {
                     JSONObject jsonObj = new JSONObject();
                     jsonObj.put("name","Hasmukh"); 
                     jsonObj.put("surname","Bhadani");
                     jsonObj.put("address","new hg road");
                    
                     JSONObject jsonObjNumber=new JSONObject();
                     jsonObjNumber.put("CellNumber","1234567890");
                     jsonObjNumber.put("HomeNumber", "9876543210");               
                     jsonObj.put("Numbers",jsonObjNumber);

                     JSONArray jsonArr = new JSONArray();
                     for (int i = 0; i < 5; i++)
                     {
                           JSONObject pnObj = new JSONObject();
                           pnObj.put("Key","Value "+i);                 
                           jsonArr.put(pnObj);              
                     }

                     jsonObj.put("ArrayName",jsonArr);

                     return jsonObj.toString();

              }
              catch(JSONException ex) {
                     ex.printStackTrace();
              }

              return null;

       }

}


You may like Parse JSON resonce visit

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)