SerializedName注释似乎在Moshi中不起作用

问题描述 投票:8回答:1

所以我试图使用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("[email protected]", "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不起作用?

android retrofit2 moshi
1个回答
16
投票

@SerializedName("accessToken")是Gson

它应该是

@Json(name="access_token")

© www.soinside.com 2019 - 2024. All rights reserved.