简体   繁体   English

具有改型和嵌套JSON响应的NPE

[英]NPE with retrofit and nested JSON response

I am using retrofit 1.9 and I'm having some trouble getting the values from nested JSON response. 我正在使用翻新1.9,但在从嵌套JSON响应中获取值时遇到了一些麻烦。 Here is the response 这是回应

{
  "access_token": "83ebeabdec09f6670863766f792ead24d61fe3f9",
  "athlete": {
    "id": 227615,
    "resource_state": 3,
    ...
  }
}

I have a class to handle the response: 我有一个类来处理响应:

public class AuthResponse {

    String accessToken;
    StravaAthlete stravaAthlete;

    public AuthResponse(String accessToken, StravaAthlete stravaAthlete) {
        this.accessToken = accessToken;
        this.stravaAthlete = stravaAthlete;
    }

    public String getAccessToken() {
        return accessToken;
    }

    public StravaAthlete getStravaAthlete() {
        return stravaAthlete;
    }
}

and a class for the nested JSON object: 和一个用于嵌套JSON对象的类:

public class StravaAthlete {

    String id;

    public StravaAthlete(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }
}

Unfortunately whenever I call authResponse.getStravaAthlete().getId() I get 不幸的是,每当我调用authResponse.getStravaAthlete().getId()我都会得到

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.drdp.rideart.api.model.StravaAthlete.getId()' on a null object reference

Not sure what I am doing wrong. 不知道我在做什么错。 I have retrofit logging set to full and can verify the information is in the response in the format I expect 我已将改造日志记录设置为已满,并且可以验证信息是否以我期望的格式包含在响应中

accessToken and StravaAthlete are not key of your JSON. accessTokenStravaAthlete不是JSON的键。 That's why you are getting null. 这就是为什么您变得空的原因。 You can either change them into access_token and athlete , or use the @SerializedName annotation. 您可以将它们更改为access_tokenathlete ,或使用@SerializedName批注。 Eg 例如

public class AuthResponse {

   @SerializedName("access_token")
   String accessToken;
   @SerializedName("athlete")
   StravaAthlete stravaAthlete;

首先,我可以在这里看到的是田径athlete的姓名,应该与您的班级stravaAthlete athlete匹配或添加注释@SerializedName(value="athlete")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM