[英]String cannot be converted to JSONObject exception
Newbie to Json here, I'm gettin a Value Database of type java.lang.String cannot be converted to JSONObject error when I try and run the following code.I cant make any sense of other answers on here. 在这里,对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();
}
This is the error 这是错误
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)
The Json you are posting is invalid, trim that {"server_response
and closing curly braces too. The remaining Json will be like this, which is valid now, 您发布的Json无效,请修剪
{"server_response
并关闭花括号。其余的Json将像这样,现在有效,
[{"code":"reg_true","message":"Sucessful registration.Thank you.Enjoy"}]
The you can parse it like here, 您可以像这里这样解析
JSONArray jsonarray = new JSONArray(json);
JSONObject jsonobject = jsonarray.getJSONObject(0);
String code = jsonobject.getString("code");
String message = jsonobject.getString("message");
UPDATE : 更新:
If your Json is as you commented then you can easily retrieve this like 如果您的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");
Your json is invalid. 您的json无效。 You can check your json on jsonlint.com Correct json should be like this
{"server_response":{"code":"reg_true","message":"Sucessful registration.Thank you.Enjoy"}}
Since you are using only one json object there is no need to create json array. 您可以在jsonlint.com上检查json正确的json应该像这样
{"server_response":{"code":"reg_true","message":"Sucessful registration.Thank you.Enjoy"}}
因为您只使用了一个json对象,无需创建json数组。
Remember if it starts with [
and ends with ]
its json array; 请记住,它是否以其json数组以
[
开头]
; with curly braces {...}
its json object. 带有花括号
{...}
的json对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.