Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

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

I am getting the error org.json.JSONException: No value for PROJECT_NAME This is my json

{"PROJECTS":[ 
         {
            "PROJECT_NUMBER": "2062",
            "PROJECT_NAME": "OPW 51183"
         },
         {
            "PROJECT_NUMBER": "404",
            "PROJECT_NAME": "404"
         },
         {
            "PROJECT_NUMBER": "2125",
            "PROJECT_NAME": "OPW 50016"
         },
         {
            "PROJECT_NUMBER": ""
         },
         {
            "PROJECT_NUMBER": "2130",
            "PROJECT_NAME": "OPW 51151 63rd & Shirley SEW S"
         },
         {
            "PROJECT_NUMBER": "2159",
            "PROJECT_NAME": "OPW 51226"
         }
        ]

    }

and cod is:

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

JSONObject obj=innerProjectarray.getJSONObject(i);
String projectnumber1=obj.getString("PROJECT_NUMBER");
String projectname1=obj.getString("PROJECT_NAME");
        }

Is there is any way to find the key if key not exist then np need to get the value od particular string Help me thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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. 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...