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.
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,
[{"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
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. 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.
Remember if it starts with [
and ends with ]
its json array; with curly braces {...}
its json object.
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.