Alireza Bideli
Alireza Bideli

Reputation: 874

How to find out json response is an empty JSON object in android?

I'm facing the problem that I get an empty JSON Object from the server.

How can I find out that JSON response from the server is an empty JSON Object {} or others? I set jObject!=null condition for it but it doesn't work.

Here is my code:

JSONObject jObject = new JSONObject(response);

if (jObject!=null) {
    Toast.makeText(getApplicationContext(), R.string.successfull_unsubscribe, Toast.LENGTH_LONG).show();
    ShareData.saveData(getApplicationContext(), "simType", "null");
    ShareData.saveData(getApplicationContext(), "firstLaunch", "true");

    startActivity(new Intent(MainActivity2.this, WelcomeActivity.class));
    finish();
}

Upvotes: 0

Views: 1231

Answers (2)

Natig Babayev
Natig Babayev

Reputation: 3296

You can use jObject.keys().hasNext() or jObject.length() != 0:

JSONObject jObject = new JSONObject(response);
if (jObject != null && jObject.length() != 0) {
    Toast.makeText(getApplicationContext(), R.string.successfull_unsubscribe, Toast.LENGTH_LONG).show();
    ShareData.saveData(getApplicationContext(), "simType", "null");
    ShareData.saveData(getApplicationContext(), "firstLaunch", "true");

    startActivity(new Intent(MainActivity2.this, WelcomeActivity.class));
    finish();
}

Upvotes: 1

Sayantan Mandal
Sayantan Mandal

Reputation: 1336

You can try length check or toString.

eg: jObject.length() == 0

eg: jObject.toString().equals("{}")

Upvotes: 1

Related Questions