简体   繁体   中英

org.json.JSONException: No value for price

I get result json and parse in android. Exception has happened with a message: org.json.JSONException: No value for price

W/System.err: org.json.JSONException: No value for price
W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
W/System.err:     at org.json.JSONObject.getString(JSONObject.java:550)

My java class

JSONParser jsonParser = new JSONParser();

// tracks JSONArray
JSONArray albums = null;

// Album id
String album_id = null;
String song_id = null;

String album_name, song_name, price;

// single song JSON url
// GET parameters album, song
private static final String URL_SONG = "my url";


// ALL JSON node names
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_ALBUM = "name";     // album
...
try {
       JSONObject jObj = new JSONObject(json);
       if(jObj != null){
            song_name = jObj.getString(TAG_NAME);
            album_name = jObj.getString(TAG_ALBUM);
            price = jObj.getString(TAG_PRICE);
       }
 } 
 catch (JSONException e) {
        e.printStackTrace();
 }

My json URL:

{
  "id": "551"
  "name": "Rent Disk"
  "price": "3233333"
  "album_id": "3"
  "album": "Michael"
}

How to fix this exception? thank so much !!

You can put a check like this before putting value

JSONObject jObj = new JSONObject(json);
if(jObj != null) {
    if(jObj.has(TAG_NAME)) {
        song_name = jObj.getString(TAG_NAME);
    }
    if(jObj.has(TAG_ALBUM)){
        album_name = jObj.getString(TAG_ALBUM);
    }
    if(jObj.has(TAG_PRICE)){
        price = jObj.getString(TAG_PRICE);
    }
}

JSONException

Thrown to indicate a problem with the JSON API

FYI

 {
  "id": "551"
  "name": "Rent Disk"
  "price": "3233333"
  "album_id": "3"
  "album": "Michael"
}

Post your Json Here

If above is your json then it is not valid .

For your requirement you should use JSONObject .has("") and .isNull("") method .

Edited

Your perfect Json is

{ "id": 551, "name": "Cho thue xe Toyota5", "price": "3233333", "album_id": "3", "album": "Huyndai" }

Try with this

 JSONObject myJson = new JSONObject(json);
 String getName = myJson.optString("name");
 int getID= myJson.optInt("id");

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