error org.json.JSONException: No value for PROJECT_NAME This is my json

   {
        "PROJECT_NUMBER": ""
     },

Here you have only "PROJECT_NUMBER", reason you have the exception. Try to find a way to deal with it.


Use has to check if key is present in Json. It returns true if this object has a mapping for name.

like

for (int i = 0; i < innerProjectarray.length(); i++) {

    JSONObject obj = innerProjectarray.getJSONObject(i);
    if (obj.has("PROJECT_NUMBER")) {
        String projectnumber1 = obj.getString("PROJECT_NUMBER");
    }

    if (obj.has("PROJECT_NAME")) {
        String projectname1 = obj.getString("PROJECT_NAME");
    }
}

Another way is to use optString which returns the value mapped by name if it exists, coercing it if necessary. Returns the empty string if no such mapping exists.

for (int i = 0; i < innerProjectarray.length(); i++) {

    JSONObject obj = innerProjectarray.getJSONObject(i);

    String projNum = obj.optString("PROJECT_NUMBER"); 
    String projName = obj.optString("PROJECT_NAME"); 
    // and use both values. 
}

You can check where key is exists or not using has() Method. below is your code look like

for (int i = 0; i < innerProjectarray.length(); i++) 
    {

     JSONObject obj=innerProjectarray.getJSONObject(i);

     if(obj.has("PROJECT_NUMBER"))
     {
      Log.i("Project Number ",obj.getString("PROJECT_NUMBER"));
     }
     else
     {
        Log.i("Project Number ","No Such Tag as PROJECT_NUMBER");
     }

     if(obj.has("PROJECT_NAME"))
     {
       Log.i("Project Name ",obj.getString("PROJECT_NAME"));
     }
     else
     {
        Log.i("Project Name ","No Such Tag as PROJECT_NAME");
     }

} 

I hope above code help you to resolve your problem


// Because if the parameter or variable is not exists into JSON object it won't execute further code and throw exception so its better to use like :

try {

            JSONObject data = coupon;



                if(data.has("event_recurring_text")) {

                    if ("".equals(data.getString("event_recurring_text"))) {

                        bundle.putString("event_time", data.getString("event_recurring_text"));

                    } else {

                        bundle.putString("event_time", data.getString("event_time"));
                    }
                }
            }// end if



        } catch (JSONException e) {

            Log.i("Handler 4","JSONException: Handled");            
            e.printStackTrace();
        }

//Here data.has() method checking whether variable exists or not into oject

//vKj

Tags:

Json

Android