JSONException: no value for XYZ when trying to getString("XYZ") JSONException: no value for XYZ when trying to getString("XYZ") json json

JSONException: no value for XYZ when trying to getString("XYZ")


Use optString instead, catching the Exception is costly and unnecessary.

public String optString (String name)

Added in API level 1 Returns the value mapped by name if it exists, coercing it if necessary. Returns the empty string if no such mapping exists.

public String optString (String name, String fallback)

Added in API level 1 Returns the value mapped by name if it exists, coercing it if necessary. Returns fallback if no such mapping exists.

Documentation


You can use ths logical solution for your problem.

Try this once.

public static String getStringFromJSON(JSONObject json, String key){    String value = ""; // Blank string by default.      try {               String value = json.getString(key);        return value;    }        catch(JSONException exp){        exp.getMessage();    }    return value;  // this wil return BLANk string if object is not prasent.}

You can you this method for getting String from json object,