Getting a string out of a JSONObject
14,961
Solution 1
Your token field is inside another JSONObject data so you'll have to do the following
yourMainObject.getJSONObject("data").getString("token");
You can also use optString() method instead of getString if you're not sure that your token will always be present
Solution 2
you should be able to get token by using this.
try {
String data = response.toString();
JSONObject jsonObject = new JSONObject(data);
String token = jsonObject.getJSONObject("data").getString("token");
System.out.println(token);
} catch (JSONException e) {
e.printStackTrace();
}
Related videos on Youtube
Author by
Diogo Carvalho
Updated on June 04, 2022Comments
-
Diogo Carvalho almost 2 years
I'm trying to get a string out of a JSONObject that I'm receiving from a request to an API.
My JSONObject is as follows:
{ "status":"success", "message":"user authenticated", "data": { "id":11, "username":"2160481", "token":"MEznhD8RE1-ykZLOdGs4i9ZfRFQl5h_" } }
I've tried some responses I found here, like the getString("token") with no success. I've also tried to create an array with the JSONObject inside and get the string from there, also with no success.
EDIT:
Try 1:
String data = response.toString(); JSONObject teste = new JSONObject(data); String status = teste.getString("status"); System.out.println(status);
Try 2:
String token = null; try { JSONArray arr = new JSONArray(); arr.put(response); JSONObject jObj = arr.getJSONObject(0); token = jObj.getString("token"); System.out.println("---> Token: " + token); } catch (JSONException e) { System.out.println("---> Error:" + e); }
Try 3:
String token = null; try { token = response.getString("token"); System.out.println("---> Token: " + token); } catch (JSONException e) { System.out.println("---> Error:" + e); }`