How to Parse a JSON Object In Android example

Hi in this, Article I am sharing How to Parse a JSON Object In AndroidJSON (JavaScript Object Notation) is the simplest data exchange formats to interchange the data from the server. In simple words, we can say that JSON is a lightweight and structured language. here you can find the full step by step guideline for how to parse JSON data and show data in UI.

Android support for all JSON format like,  JSONObjectJSONArrayJSONStringer, etc. to parse the JSON data to get a piece of required information in android applications.

The main advantage of JSON is, it’s a language-independent and the JSON object will contain data like key/value pair.

Sample structure of JSON data in android applications.

 
   "message":"Profile successfully view!",
   "status":"1",
   "allData": 
      "id":5,
      "registration_no":"100005_GUR_TH",
      "name":"Ashita",
      "email":"ashita@gmail.com",
      "gender":"female",
      "mobile":"1234567890",
      "state":"13",
      "city":"1126",
      "dob":"2019-03-11",
      "branch":"2",
      "user_type":"5",
      "profile_pic":"dYCJd4l7NBeVEbB.jpg",
      "adhar_card":"PjioeLWRMQyoHki.pdf",
      "degree":"",
      "base_commision":"20",
      "occupation":"",
      "age":"0 Years",
      "stateName":"Haryana",
      "cityName":"Gurgaon",
      "branchName":"Delhi Panel",
      "profile_pics":"http:\/\/caprispine.org\/public\/upload\/profile_pic\/dYCJd4l7NBeVEbB.jpg",
      "degrees":""
   }
}

 

Android JSON Parsing Example

in this example of parsing the JSON string and get the required information from it using JSON String format. Create a new android application using an android studio, and using volley library for getting data for API.

Step 1: Create an Activity Name Profile. 

in this activity, I am sharing a JSONObject response Using API data show in this activity. with a nice UI.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:28.+'
    compile 'com.android.support:design:28.+'
    compile 'com.android.support:support-v4:28.+'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

 Step 2: Create A Profile UI In your activity_profile.xml.

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/back"
    tools:context="com.codeplayon.Profile">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:paddingRight="5dp"
        android:orientation="vertical">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/Profile"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_gravity="right"
            android:layout_marginTop="50dp"
            android:src="@drawable/icon_user"
            android:tint="@color/colorAccent"
            app:civ_border_color="@color/colorAccent"
            app:civ_border_width="2dp" />


        <TextView
            android:id="@+id/FirstName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="2dp"

            android:layout_marginTop="5dp"
            android:textStyle="bold"
            android:singleLine="true"
            android:text=""
            android:gravity="right"
            android:textAppearance="?android:textAppearanceMedium" />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:padding="2dp"
                android:layout_height="wrap_content"
                android:text=" Reg No: "
                android:gravity="right"
                android:textStyle="bold"
                android:singleLine="true"
                android:textAppearance="?android:textAppearanceSmall" />

            <TextView
                android:id="@+id/Reg_No"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textStyle="bold"
                android:singleLine="true"
                android:gravity="right"
                android:text=""
                android:textAppearance="?android:textAppearanceSmall"
                />

        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:padding="2dp"
                android:layout_height="wrap_content"
                android:text=" Branch: "
                android:gravity="right"
                android:textStyle="bold"
                android:singleLine="true"
                android:textAppearance="?android:textAppearanceSmall" />

            <TextView
                android:id="@+id/BranchName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textStyle="bold"
                android:singleLine="true"
                android:gravity="right"
                android:text=""
                android:textAppearance="?android:textAppearanceSmall"
                />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:padding="2dp"
                android:layout_height="wrap_content"
                android:text=" Email Id:"
                android:gravity="right"
                android:textStyle="bold"
                android:singleLine="true"
                android:textAppearance="?android:textAppearanceSmall" />

            <TextView
                android:id="@+id/EmailName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textStyle="bold"
                android:singleLine="true"
                android:gravity="right"
                android:text=""
                android:textAppearance="?android:textAppearanceSmall"
                />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:padding="2dp"
                android:layout_height="wrap_content"
                android:text="Mobile No:"
                android:gravity="right"
                android:textStyle="bold"
                android:singleLine="true"
                android:textAppearance="?android:textAppearanceSmall" />

            <TextView
                android:id="@+id/Mobile"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textStyle="bold"
                android:singleLine="true"
                android:gravity="right"
                android:text=""
                android:textAppearance="?android:textAppearanceSmall"
                />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:gravity="right"
                android:textStyle="bold"
                android:singleLine="true"
                android:text="Gender:"
                android:textAppearance="?android:textAppearanceSmall"
                />

            <TextView
                android:id="@+id/GenderName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:gravity="right"
                android:textStyle="bold"
                android:singleLine="true"
                android:text=""
                android:textAppearance="?android:textAppearanceSmall"
                />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:gravity="right"
                android:textStyle="bold"
                android:singleLine="true"
                android:text="D.O.B :"
                android:textAppearance="?android:textAppearanceSmall"
                />

            <TextView
                android:id="@+id/DobName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:gravity="right"
                android:textStyle="bold"
                android:singleLine="true"
                android:text=""
                android:textAppearance="?android:textAppearanceSmall"
                />
        </LinearLayout>

        <TextView
            android:id="@+id/Agency_Address"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:maxLines="6"
            android:layout_marginLeft="85dp"
            android:gravity="right"
            android:textStyle="bold"
            android:text=""
            android:textAppearance="?android:textAppearanceSmall" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="bottom"
        android:paddingBottom="5dp"
        android:paddingRight="5dp"
        android:layout_weight="1.5"
        android:orientation="vertical">

        <ImageView
            android:layout_width="180dp"
            android:layout_height="70dp"
            android:layout_gravity="right"
            android:src="@drawable/app_icon"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textStyle="italic"
            android:gravity="right"
            android:padding="0dp"
            android:textColor="@color/colorPrimary"
            android:textAppearance="?android:textAppearanceMedium"
            android:text="CodePlayon"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textStyle="italic"
            android:gravity="right"
            android:padding="0dp"
            android:textColor="@color/colorAccent"
            android:textAppearance="?android:textAppearanceSmall"
            android:text="Share , Learn , and Explore "/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textStyle="italic"
            android:gravity="right"
            android:padding="5dp"
            android:textAppearance="?android:textAppearanceSmall"
            android:text="Ph.: +91-9671718285,  1234567890"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginLeft="100dp"
            android:background="@color/colorPrimary"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textStyle="italic"
            android:gravity="right"
            android:padding="0dp"
            android:textAppearance="?android:textAppearanceSmall"
            android:text="Website : www.techplayon.com"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textStyle="italic"
            android:gravity="right"
            android:padding="0dp"
            android:textAppearance="?android:textAppearanceSmall"
            android:text="Website : www.codeplayon.com"/>


        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textStyle="italic"
            android:gravity="right"
            android:padding="0dp"
            android:textAppearance="?android:textAppearanceSmall"
            android:text="E-mail: codeplayonapp@gmail.com"/>

        </LinearLayout>


        </LinearLayout>
    </ScrollView>
</LinearLayout>

 

Step 3: Open You Java Profile.java Class And Call API and get JsonObject Data.

public class Profile extends AppCompatActivity {
    public static final String KEY_EMAIL="userId";
    public static String EMAIL;
    TextView TxName,TxEmail,TxMobile,TxAddress,TxReg_No,TxBranchName,TextGender,TxDobName;
    ImageView ProfileImage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        SessionManagement sessionManagement=new SessionManagement(); //log in page session if user is all
        Boolean isLoggedIn=sessionManagement.getLogin(Profile.this);
        EMAIL = sessionManagement.getSavedEmail(Profile.this);
        if (!isLoggedIn){
            Intent intent = new Intent(Profile.this,Signin_Activity.class);
            startActivity(intent);
        }

        if (AppStatus.getInstance(this).isOnline()) {
            VendorProfile();
        } else {
            ContextThemeWrapper ctw = new ContextThemeWrapper( Profile.this, R.style.Theme_AlertDialog);
            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
            alertDialogBuilder.setTitle("No internet connection");
            alertDialogBuilder.setMessage("Check your  internet connection or try again");
            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                }
            });
            alertDialogBuilder.show();
        }
        TxName=(TextView)findViewById(R.id.FirstName);
        TxEmail=(TextView)findViewById(R.id.EmailName);
        TxMobile=(TextView)findViewById(R.id.Mobile);
        TxAddress=(TextView)findViewById(R.id.Agency_Address);
        ProfileImage=(ImageView)findViewById(R.id.Profile);
        TextGender=(TextView)findViewById(R.id.GenderName);
        TxReg_No=(TextView)findViewById(R.id.Reg_No);
        TxBranchName=(TextView)findViewById(R.id.BranchName);
        TxDobName=(TextView)findViewById(R.id.DobName);
    }

    private void VendorProfile(){
        final ProgressDialog loading = new ProgressDialog(Profile.this);
        loading.setMessage("Please Wait...");
        loading.show();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, ConfiURL.Profile_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            Log.d("JSON", response);
                            loading.dismiss();
                            JSONObject jsonObject = new JSONObject(response);
                            String error_status = jsonObject.getString("status");
                            if (error_status.equals("0")) {
                                String error_msg = jsonObject.getString("message");
                                Toast.makeText(Profile.this,error_msg,Toast.LENGTH_LONG).show();
                            } else {
                                JSONObject userDetails = jsonObject.getJSONObject("allData");
                                String registration_no=userDetails.getString("registration_no");
                                String FirstName = userDetails.getString("name");
                                String Email = userDetails.getString("email");
                                String Phone = userDetails.getString("mobile");
                                String gender = userDetails.getString("gender");
                                String dob=userDetails.getString("dob");
                                String state = userDetails.getString("stateName");
                                String city = userDetails.getString("cityName");
                                String branchName = userDetails.getString("branchName");
                                String Image = userDetails.getString("profile_pics");
                                TxReg_No.setText(registration_no);
                                TxBranchName.setText(branchName);
                                TxName.setText(FirstName);
                                TxMobile.setText(Phone);
                                TxEmail.setText(Email);
                                TextGender.setText(gender);
                                TxDobName.setText(dob);
                                TxAddress.setText("City: "+city+", "+"State: "+state);
                                Picasso.with(Profile.this)
                                        .load(Image)
                                        .placeholder(R.drawable.icon_user)
                                        .into(ProfileImage);

                            }
                        }catch (Exception e) {
                            Log.d("Tag", e.getMessage());

                        }
                    }
                },

                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        loading.dismiss();
                        if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper( Profile.this, R.style.Theme_AlertDialog);
                            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("No connection");
                            alertDialogBuilder.setMessage(" Network timeout connection error please try again ");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            alertDialogBuilder.show();
                        } else if (error instanceof AuthFailureError) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper( Profile.this, R.style.Theme_AlertDialog);
                            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("Connection Error");
                            alertDialogBuilder.setMessage("Connection authentication failure  error please try again");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {


                                }
                            });
                            alertDialogBuilder.show();
                            //TODO
                        } else if (error instanceof ServerError) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper( Profile.this, R.style.Theme_AlertDialog);
                            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("Connection Error");
                            alertDialogBuilder.setMessage("Connection error please try again");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            alertDialogBuilder.show();
                            //TODO
                        } else if (error instanceof NetworkError) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper( Profile.this, R.style.Theme_AlertDialog);
                            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("Connection Error");
                            alertDialogBuilder.setMessage("Network connection error please try again");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            alertDialogBuilder.show();
                            //TODO
                        } else if (error instanceof ParseError) {
                            ContextThemeWrapper ctw = new ContextThemeWrapper( Profile.this, R.style.Theme_AlertDialog);
                            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ctw);
                            alertDialogBuilder.setTitle("Error");
                            alertDialogBuilder.setMessage("Parse error");
                            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            alertDialogBuilder.show();
                        }
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(KEY_EMAIL, EMAIL);
                return map;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(Profile.this);
        requestQueue.add(stringRequest);
    }

    public void onBackPressed(){
        Intent intent=new Intent(Profile.this,Home.class);
        startActivity(intent);
        finish();
    }

 

 

 

 

You may also like...