I am trying to correctly get a string by using a key in the json format input. Basically the api(that I get the json format input) produces its output such as {"status":"ok","token":"lskjfajsdkfjasldf"}
.
I here encounter the conversion error from String to JSONObject when trying to get a status ("ok") using key ("status"). I changed JSONObject into Array and recall [0] component but it didn't work and I am completely lost here. Below is my code and error log.
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line).append("\n");
}
reader.close();
connection.disconnect();
String json = buffer.toString();
JSONObject obj = new JSONObject(json);
return obj.getString("token");
Below is the error message.
Value {"status":"ok","token":"lskjfajsdkfjasldf"} of type java.lang.String cannot be converted to JSONObject org.json.JSONException: Value {"status":"ok","token":"tZwmfc_NbamK2reyAxR7"} of type java.lang.String cannot be converted to JSONObject
Please give me any hint or opinion how to approach to fix this problem! Thanks for reading this question!
Although there are links that answer this type of question, the answer there doesn't work.