![](/img/trans.png)
[英]JSON Exception: java.lang.String cannot be converted to JSONObject
[英]String cannot be converted to JSONObject exception
在這里,對Json來說是新手,我試圖運行以下代碼時無法將java.lang.String類型的值數據庫轉換為JSONObject錯誤。
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JN = jsonArray.getJSONObject(0);
String code =JN.getString("code");
String message = JN.getString("message");
if (code.equals("reg_true"))
{
showDialog("Your Registration has been successful.",message,code);
}
else if (code.equals("reg_false"))
{
showDialog("Your Registration Failed.",message,code);
}
} catch (JSONException e){
e.printStackTrace();
}
這是錯誤
W/System.err﹕ org.json.JSONException: Value Database of type java.lang.String cannot be converted to JSONObject
W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:160)
W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:173)
W/System.err﹕ at com.example.project.BackgroundTask.onPostExecute(BackgroundTask.java:133)
W/System.err﹕ at com.example.project.BackgroundTask.onPostExecute(BackgroundTask.java:29)
您發布的Json無效,請修剪{"server_response
並關閉花括號。其余的Json將像這樣,現在有效,
[{"code":"reg_true","message":"Sucessful registration.Thank you.Enjoy"}]
您可以像這里這樣解析
JSONArray jsonarray = new JSONArray(json);
JSONObject jsonobject = jsonarray.getJSONObject(0);
String code = jsonobject.getString("code");
String message = jsonobject.getString("message");
更新:
如果您的Json符合您的評論,那么您可以像這樣輕松檢索
JSONObject jobject = new JSONObject(json);
JSONArray jsonarray = jobject.getJSONArray("server_response");
JSONObject jsonobject = jsonarray.getJSONObject(0);
String code = jsonobject.getString("code");
String message = jsonobject.getString("message");
您的json無效。 您可以在jsonlint.com上檢查json正確的json應該像這樣{"server_response":{"code":"reg_true","message":"Sucessful registration.Thank you.Enjoy"}}
因為您只使用了一個json對象,無需創建json數組。
請記住,它是否以其json數組以[
開頭]
; 帶有花括號{...}
的json對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.