首页 > 解决方案 > Android - Populate values into already created POJO model object using retrofit

问题描述

I have a POJO model object "apiResponse" that has values from a previous API call.

{
   "status":200,
   "userModel":{
                 ...SOME VARIABLES...
               },
   "otherContentRelatedToUserModel":{
                    ..SOME RELATED CONTENT..
                    }
}

This apiResponse has an "UserModel" as an inner object.

What i want to do is pass this "apiResponse" object to another api call whose response is "UserModel", and have it update only the UserModel object in the APIResponse POJO object.

The objective is to keep a single source of related content, which could change based on the interaction in the application, but might not update the rest of the related content.

Or is it possible to atleast update an already created pojo model as a whole, updating the variable values in the model.?

Reason for this ::

The API's content does not change for a set amount of time in the server, mainly to avoid over traffic to the server. So some amount of logic has to be implemented on the application side. Currently using a DB is not really a viable option.

Basically update only a portion of the already created POJO class object with another api call.

Is this possible in android(kotlin) using retrofit? Or is there any other way this could be achievable?

标签: androidkotlinretrofit2

解决方案


我认为不可能UserModel通过使用来填充现有对象中的附加字段Retrofit,但您可以使用以下方法做一些魔术GSON

data class UserModel(
        val userId: Int? = null,
        val userName: String? = null)

class OtherContentRelatedToUserModel

data class ApiResponsePojo(
        val status: Int? = null,
        val userModel: UserModel? = null,
        val otherContentRelatedToUserModel: OtherContentRelatedToUserModel? = null)

class UserModelInstanceCreator(var userModelToUpdate: UserModel? = null)
    : InstanceCreator<UserModel> {
    override fun createInstance(type: Type?): UserModel {
        return userModelToUpdate ?: UserModel()
    }
}

val apiResponseJson =
        """
            {
                "status":200,
                "userModel":{
                    "userId": 1
                },
                "otherContentRelatedToUserModel":{
                }
            }
        """

val userModelResponseJson =
        """
            {
                "userName": "john wick"
            }
        """

val userModelInstanceCreator = UserModelInstanceCreator()

val gson = GsonBuilder()
        .registerTypeAdapter(UserModel::class.java, userModelInstanceCreator)
        .create()

val apiResponse: ApiResponsePojo = gson.fromJson(apiResponseJson, ApiResponsePojo::class.java)
userModelInstanceCreator.userModelToUpdate = apiResponse.userModel
gson.fromJson(userModelResponseJson, UserModel::class.java)

...
// apiResponse.toString() result
// ApiResponsePojo(status=200, userModel=UserModel(userId=1, userName=john wick)...

推荐阅读