简体   繁体   中英

org.json.JSONException: No value for custom

Guys any help thanks in project i got error like this

my json data

{"time": "1422282109", "time_pretty": "Mon Jan 26 2015, 6:21am", "time_total": "10", "ip_address": "107.5.167.0", "uid": "1692954453", "session_id": "1094364389", "actions": "1", "total_visits": "2", "first_visit": {}, "landing_page": "http://clicky.com/blog/", "web_browser": "Safari 8.0", "operating_system": "Mac OS X", "screen_resolution": "1280x800", "javascript": "1", "language": "English", "geolocation": "Macomb, MI, USA", "country_code": "us", "latitude": "42.6735", "longitude": "-82.9165", "hostname": "comcast.net", "organization": "Comcast Cable", "custom": { "username": "finnllow" }

when i tried to access username got error like this

Error

org.json.JSONException: Value {"username":"jprezzi"} at custom of type org.json.JSONObject cannot be converted to JSONArray

My code

JSONArray cus = vvObj.getJSONArray(TAG_OBJ_CUSTOM);
    String getUserName = "";
    for (int f = 0; f < cus.length(); f++) {
       JSONObject cud = cus.getJSONObject(f);
       getUserName = cud.getString(TAG_OBJ_USERNAME);
    }

i tried direct json object but there is also error

org.json.JSONException:no value for custom

Code

JSONObject cutom = vvObj.getJSONObject("custom");
String name = custom.getString("username");

EDIT i got my problem solved

the problem is sometimes in username key the value is not set in JSON data for that is used optString , using this when value is not present it won't through error

Custom isn't a JSONArray , it is a JSONObject . So when you try to convert the JSONObject custom to a JSONArray , you get an exception. To get the username field out of the custom object, use:

JSONObject cus = vvObj.getJSONObject(TAG_OBJ_CUSTOM);
String getUserName = "";
getUserName = cus.getString(TAG_OBJ_USERNAME);

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