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();
}
Share:
14,961

Related videos on Youtube

Diogo Carvalho
Author by

Diogo Carvalho

Updated on June 04, 2022

Comments

  • Diogo Carvalho
    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);
        }`