Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SerializedName annotation doesn't seem to work in Moshi

So I'm trying to parse a call from my server using Moshi. This is my response object.

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;

}

This is my endpoint definition (not really important but I'll include it anyway)

public interface ServerService {

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

    }

And this is the code I'm using to call.

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?
                }
            }
        });

In the onResponse method, my response.body() always has accessToken, issued and expires as null. I get values back for the other parameters. Using the Android Profiler, I know for certain that it's returning this as the response.

{  
   "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\"]"
}

So what am I doing wrong? Why isn't SerializedName working?

like image 574
Diskdrive Avatar asked Dec 20 '17 00:12

Diskdrive


1 Answers

@SerializedName("accessToken") is Gson

It should be

@Json(name="access_token")

like image 195
Diskdrive Avatar answered Oct 16 '22 10:10

Diskdrive