android - 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?
解决方案
我认为不可能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)...
推荐阅读
- reactjs - 如何在 gatsby 中使用谷歌标签管理器
- javascript - node_modules 包导入上的意外标识符
- angular - 如何在模板驱动的表单中获取表单组验证结果?
- c++ - 有什么方法可以创建用户定义的类型修饰符?
- python - 为什么随机数永远不会等于 4.0?
- java - 使用冒泡排序和交换方法对双向链表进行排序
- c++ - 仅在一个构造函数上的类成员初始化程序中的隐式常量转换 [-Werror=overflow] 溢出
- amazon-web-services - 无需密码的 AWS Cognito 身份验证,用于后端服务器-服务器调用
- apache - Htaccess IP地址拒绝限制
- sockets - segs_out 与 data_segs_out 和 segs_in 与 data_segs_out