25

所以我正在尝试使用 Moshi 解析来自我的服务器的调用。这是我的响应对象。

public class TokenResponse {
    @SerializedName("accessToken")
    public String accessToken;
    public String token_type;
    public int expires_in;
    public String userName;
    public String name;
    @SerializedName(".issued")
    public String issued;
    @SerializedName(".expires")
    public String expires;
    public String Roles;

}

这是我的端点定义(不是很重要,但无论如何我都会包含它)

public interface ServerService {

        @POST("/token")
        @FormUrlEncoded
        Call<TokenResponse> getToken(@Field("username") String username,
                                    @Field("password") String password, @Field("grant_type") String grant_type);

    }

这是我用来调用的代码。

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://xxx/")
                .addConverterFactory(MoshiConverterFactory.create())
                .build();

        ServerService service = retrofit.create(ServerService.class);

        Call<TokenResponse> call = service.getToken("admin@admin.com", "password1!", "password");

        call.enqueue(new Callback<TokenResponse>() {
            @Override
            public void onResponse(Call<TokenResponse> call, Response<TokenResponse> response) {
                if (response.isSuccessful()) {
                    // tasks available
                    TextView tv = (TextView)findViewById(R.id.tvToken);
                    tv.setText(response.body().accessToken);


                } else {
                    // error response, no access to resource?
                }
            }
        });

在 onResponse 方法中,我的 response.body() 总是有 accessToken,发出并过期为 null。我得到了其他参数的值。使用 Android Profiler,我确定它会将其作为响应返回。

{  
   "access_token":"_xxx",
   "token_type":"bearer",
   "expires_in":1209599,
   "userName":"xxx",
   "name":"LOURDES RILEY",
   ".issued":"Tue, 19 Dec 2017 23:37:06 GMT",
   ".expires":"Tue, 02 Jan 2018 23:37:06 GMT",
   "Roles":"[\"Admin\"]"
}

那么我做错了什么?为什么 SerializedName 不起作用?

4

1 回答 1

58

@SerializedName("accessToken")是格森

它应该是

@Json(name="access_token")

于 2017-12-20T00:13:33.723 回答