使用moshi反序列化JSON API响应

时间:2017-11-21 10:57:55

标签: json retrofit2 json-deserialization json-api moshi

在反序列化null响应后,我获得了json个对象属性。 在android下开发,我使用retrofit2,moshi作为转换器(https://github.com/kamikat/moshi-jsonapi)。 调试时,我看到完全检索到json响应(非null属性),但反序列化失败。我应该使用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来电,响应包含UserModelnull属性(反序列化失败,没有任何错误)

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;

我在调试http响应时看到的json响应,我没有任何麻烦地检索,但是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"
                    }
                }
            }
        }
    ]
}

1 个答案:

答案 0 :(得分:1)

我在很多小时后找到解决方案: 我应该使用“Document”而不是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) {

希望有所帮助