简体   繁体   中英

Error converting JSONArray to JSONObject

I am trying to extract and process some JSON data, but it is erroring when I try. This is my code:

protected void onPostExecute(String s) {
    String err=null;
    try {
        JSONObject root = new JSONObject(s);
        JSONObject user_data = root.getJSONObject("user_data");
        LASTNAME = user_data.getString("lastname");
        PASSWORD = user_data.getString("password");
        EMAIL = user_data.getString("email");
    } catch (JSONException e) {
        e.printStackTrace();
        err = "Exception: "+e.getMessage();
    }
    Intent i = new Intent(ctx, MainActivity.class);
    i.putExtra("lastname", LASTNAME);
    i.putExtra("email", EMAIL);
    i.putExtra("password", PASSWORD);
    i.putExtra("err", err);
    startActivity(i);
}

But this is the error:

org.json.JSONException: Value [] at user_data of type org.json.JSONArray cannot be converted to JSONObject

错误输出

I think you have problem with casting Array to Object.

[..] means it is JSONArray.

{..} means it is JSONObject.

try {
    JSONArray jObj = new JSONArray(json);
    //This is how you get value from 1 element in JSONArray
    String firstObjectValue = jObj.getString(0);

} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

If you looking for value need you to iterate all JSONArray by doing some simple loop.

JSONObject jsonObject = null;
     try {
         jsonObject = new JSONObject(result);
         JSONArray jsonARRAY = jsonObject.getJSONArray("nameOfJSONArray");
         for (int i = 0; i < jsonARRAY.length(); i++) {
             JSONObject jsonOBJECT = (JSONObject) jsonARRAY.get(i);
             String yourValue = jsonOBJECT.getString("valueKey");

         }
     } catch (JSONException e) {
         e.printStackTrace();
     }

It seems like your "user_data" is coming as json array instead of json object that you are trying to access.

you can use root.optJSONObject("user_data") to determine & return json object if your user_data is json object or will return null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM