How to check if a Json Key exist in Android

If you have worked with Json data or parsing unstructured Json object, you might have the need to check if a Json Key exist before you intend to retrieve its value.

Your application can throw an exception or return empty/null value if you try to retrieve a value that does not exist in an object.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to check if a Json Key exist in Android.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical" 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"
    tools:context=".json.Json11">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check if JSON Key Exist"
        android:layout_gravity="center_horizontal"
        android:textSize="16sp"/>

</LinearLayout>

MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;


import org.json.JSONException;
import org.json.JSONObject;

public class Json11 extends AppCompatActivity {

    private static final String TAG = Json11.class.getSimpleName();
    String jsonStr = " { \"name\":\"James\" }";
    String name, firstname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json11);

        try {
            JSONObject object = new JSONObject(jsonStr);

            //Check if key exist
            if (object.has("name")){
                name = object.getString("name");
                Toast.makeText(getApplicationContext(), "Key exist", Toast.LENGTH_LONG).show();
            } else {
                name = "John";
            }

            if (object.has("surname")){
                firstname = object.getString("surname");
                Toast.makeText(getApplicationContext(), "Key does not exist", Toast.LENGTH_LONG).show();
            } else {
                firstname = "Doe";
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.w(TAG, e.getMessage());
        }
    }
}

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment