我的 Android 应用程序中有这样的 JSON:
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJtZWhkaS5hZ291emFsQGdtYWlsLmNvbSIsImV4cCI6MTQ2ODU1NTU4MjQ5MX0.A6-xNIZdbPv9mpjLO9jnnfbAeq1y-DC08SBUt2xBnYo",
"expires": 1468555582491,
"user": {
"imageURL": "http://app.com/images/null",
"email": "mail@gmail.com",
"firstname": "mister",
"lastname": "lalalala",
"password": "$2a$10$VDGtxjz9w7f170Wc66OJi.1T",
"id": "c19349c4044d34333",
"language": "EN",
"createdAt": "2015-07-07T14:15:54.000Z",
"updatedAt": "2016-05-06T08:25:20.000Z"
}
}
我可以像这样访问“ token ”:
String json = new String(bytes);
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("debug", "TOKEN : " + jsonObj.getString("token"));
但是我不知道如何获取用户的电子邮件或名字。 我该怎么做?
谢谢
最佳答案
使用getJSONObject(String name)获取“用户”对象,然后在生成的 JSONObject 上使用 getString(String name)
:
String json = new String(bytes);
JSONObject jsonObj = null;
JSONObject userObj = null;
try {
jsonObj = new JSONObject(json);
userObj = jsonObj.getJSONObject("user");
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("debug", "firstname : " + userObj.getString("firstname"));
附言
如果你想真正正确地反序列化 JSON,我建议你开始使用 POJOs .通过这种方式,您可以将 JSON 字符串转换为可以与之交互的实际 Java 对象。例如,使用 JSON 库 GSON :
响应类:
public class Response {
public String token;
public Long expires;
public User user;
}
用户类:
public class User {
public String imageURL;
public String email;
public String firstname;
public String lastname;
public String password;
public String id;
public String language;
public Date createdAt;
public Date updatedAt;
}
反序列化代码:
Gson gson = new Gson();
Response response = gson.fromJson( jsonString, Response.class );
User user = response.user;
Log.d("debug", "firstname : " + user.firstname;
关于android - 在另一个 JSON 对象中访问一个 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37101772/