2

在对响应进行反序列化后,我得到了一个null对象属性。json在android下开发,我使用retrofit2moshi作为转换器(https://github.com/kamikat/moshi-jsonapi)。调试时,我看到json完全检索到响应(不是空属性),但反序列化失败。我应该GSON改用吗?

这是我用来json打电话的改造建造者:(没问题)

public static JsonServerInterface getSimpleClient(){

     Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_AUTH_URL)a
            .addConverterFactory(MoshiConverterFactory.create())
            .build();
   JsonServerInterface webServer=retrofit.create(JsonServerInterface.class);
   return webServer;     
}

我的api json电话,响应包含 UserModel属性null(反序列化失败,没有任何错误)

signInCall.enqueue(new Callback<UserModel>(){
  @Override
  public void onResponse
  (Call<UserModel> call, Response<UserModel> response)
  {
    response.message();
  }
}

我的UserModel(按照 moshi 的要求,但我认为它缺少一些东西):

@JsonApi(type = "users")
public class UserModel extends Resource {

@Json(name = "auth-token")
private String authToken;
@Json(name = "firstname")
private String firstname;
@Json(name = "lastname")
private String lastname;
@Json(name = "email")
private String email;
@Json(name = "created-at")
private String createdAt;
@Json(name = "updated-at")
private String updatedAt;

private HasMany<ActivityModel> activities;

json在调试 http 响应时看到的响应,我没有任何麻烦地检索,但是 moshi 很糟糕地反序列化它,并且没有引发错误:

{
    "data": {
        "id": "21",
        "type": "users",
        "attributes": {
            "auth-token": "t8S3BTqyPwN3T4QDMY1FwEMF",
            "firstname": "aymen",
            "lastname": "myself",
            "email": "aymen.myself@gmail.com",
            "created-at": "2017-11-13T22:52:39.477Z",
            "updated-at": "2017-11-13T23:21:09.706Z"
        },
        "relationships": {
            "activities": {
                "data": [
                    {
                        "id": "81",
                        "type": "activities"
                    }
                ]
            }
        }
    },
    "included": [
        {
            "id": "81",
            "type": "activities",
            "attributes": {
                "title": "activity 10",
                "description": "how to draw a circle",
                "start-at": "2017-11-13T23:06:13.474Z",
                "duration": 10,
                "created-at": "2017-11-13T23:06:32.630Z",
                "updated-at": "2017-11-13T23:06:32.630Z"
            },
            "relationships": {
                "user": {
                    "data": {
                        "id": "21",
                        "type": "users"
                    }
                }
            }
        }
    ]
}
4

1 回答 1

1

很多小时后我找到了解决方案:我应该使用“文档”而不是 UserModel

界面:

 @POST("sign-in.json")
    Call<Document> signIn(@Body Credentials credentials);

打电话时:

   signInCall.enqueue(new Callback<Document>(){
            @Override
            public void onResponse(Call<Document> call, Response<Document> response) {

希望能帮助到你

于 2017-11-21T22:55:16.830 回答