gson 将Retrofit与Rails API配合使用

6fe3ivhb  于 2022-11-23  发布在  其他
关注(0)|答案(2)|浏览(234)

我正在开发一个Android应用程序。我决定使用Square的Retrofit库,它符合我的要求。但是我面临着反序列化问题。我的后端是使用rails-api gem在Rails 4中编写的。active-model-serializer生成这种JSON(JSON有一个根元素):

{"user":{"id":1,"name":"Saygun","github_url":"www.github.com/saygun" }}

下面是初始化retrofit的方法。

public class User {

    private String mId;
    private String mName;
    private String mGithubUrl;

    public String getId() {
        return mName;
    }

    public void setId(String id) {
        this.mId = id;
    }

    public String getName() {
        return mName;
    }

    public void setName(String name) {
        this.mName = name;
    }

    public String getGithubUrl(String url) {
        this.mGithubUrl = url;
    }
}

public interface RestService {

    @GET("/users/{id}")
    void getUser(@Path("id") int id, Callback<User> cb);
}

Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .registerTypeAdapter(Date.class, new DateTypeAdapter()) .create();

RestAdapter restAdapter = new RestAdapter.Builder()
        .setEndpoint(BuildConfig.API_ENDPOINT)
        .setLogLevel(RestAdapter.LogLevel.FULL)
        .setRequestInterceptor(requestInterceptor)
        .setConverter(new GsonConverter(gson))
        .build();

RestService service = restAdapter.create(RestService.class);
service.getUser(1, new Callback<User>() {
     @Override
     public void success(User user, Response response) {
          //User is null
     }

     @Override
     public void failure(RetrofitError error) {

     }
});

有没有人能告诉我我缺少什么。为什么retrofit无法创建用户?

jogvjijk

jogvjijk1#

因为我认为你应该使用相同的名称为您的字段作为API类和实现串行化在您的客户端类。
就像这样:

public class User implements Serializable {

public String id ;
public String name;
public String github_url;

}

或者您也可以使用@SerializedName(“serialized_name”)
就像这样:

public class User implements Serializable {
    @SerializedName()
    private String mId;

    @SerializedName()
    private String mName;

    @SerializedName()
    private String mGithubUrl;
}
of1yzvn4

of1yzvn42#

这是我的解决方案(kotlin版本)

class UserModel(
    val id: Long,
    val name: String,
    val githubUrl: String
)

class UserResponse(
    @SerializedName("user") val model: UserModel
)

class PagedUserListResponse(
    val metaData: PageMetaData,
    @SerializedName("users") val items: List<UserModel>
) : PageMeta by metaData

interface PageMeta {
    val totalPages: Int
    val currentPage: Int
    val count: Int
    val previousPage: Int
    val nextPage: Int
}

class PageMetaData(
    override val totalPages: Int,
    override val count: Int,
    override val previousPage: Int,
    override val nextPage: Int,
    override val currentPage: Int
) : PageMeta

interface UserAPICaller {

    @GET("users")
    suspend fun index(@Query("page") page: Int?, @Query("per_page") perPage: Int?): PagedUserListResponse

    @POST("users")
    suspend fun create(@Body request: UserRequest): UserResponse

    @PATCH("users/{id}")
    suspend fun update(@Path("id") id: Long, @Body request: UserRequest): UserResponse
}

相关问题