从JSONObject中获取字符串 [英] Getting a string out of a JSONObject
问题描述
我正在尝试从请求API的JSONObject中获取一个字符串。
I'm trying to get a string out of a JSONObject that I'm receiving from a request to an API.
我的JSONObject如下:
My JSONObject is as follows:
{
"status":"success",
"message":"user authenticated",
"data": { "id":11,
"username":"2160481",
"token":"MEznhD8RE1-ykZLOdGs4i9ZfRFQl5h_"
}
}
我尝试了一些我在这里找到的回复,比如getString(token)没有成功。我也尝试在里面创建一个带有JSONObject的数组并从中获取字符串,但也没有成功。
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.
编辑:
尝试1:
String data = response.toString();
JSONObject teste = new JSONObject(data);
String status = teste.getString("status");
System.out.println(status);
尝试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);
}
尝试3:
String token = null;
try {
token = response.getString("token");
System.out.println("---> Token: " + token);
} catch (JSONException e) {
System.out.println("---> Error:" + e);
}`
推荐答案
您的令牌字段在里面另一个JSONObject数据,所以你必须执行以下操作
Your token field is inside another JSONObject data so you'll have to do the following
yourMainObject.getJSONObject("data").getString("token");
如果您不确定您的令牌将是否也可以使用optString()方法而不是getString永远存在
You can also use optString() method instead of getString if you're not sure that your token will always be present
这篇关于从JSONObject中获取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!