Getting a string out of a JSONObject

java android json rest

5122 观看

3回复

95 作者的声誉

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);
    }`
作者: Diogo Carvalho 的来源 发布者: 2017 年 12 月 27 日

回应 3


1

4121 作者的声誉

决定

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

作者: Kushan 发布者: 2017 年 12 月 27 日

2

4560 作者的声誉

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();
    }
作者: vikas kumar 发布者: 2017 年 12 月 27 日

0

48 作者的声誉

Just use a library that serialize/deserialize POJO to Java Objects.

Like gson : https://github.com/google/gson

作者: Vincent Etienne 发布者: 2017 年 12 月 27 日
32x32