我得到结果json和解析在android。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"
}
如何修复这个异常?非常感谢!!
你可以在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
抛出表示JSON API有问题
供参考
{
"id": "551"
"name": "Rent Disk"
"price": "3233333"
"album_id": "3"
"album": "Michael"
}
上传Json Here
如果上面是你的json,那么是无效的。
对于您的需求,您应该使用JSONObject .has("") and .isNull("")
方法。
你的完美Json是
{ "id": 551, "name": "Cho thue xe Toyota5", "price": "3233333", "album_id": "3", "album": "Huyndai" }
试试这个
JSONObject myJson = new JSONObject(json);
String getName = myJson.optString("name");
int getID= myJson.optInt("id");