Reputation: 2773
I am attempting to populate a Kotlin data class from a corresponding string value. I looked at: Kotlin Data Class from Json using GSON but what I am attempting to do is not tracking exactly the same:
fun convertStringToObject(stringValue: String?, clazz: Class<*>): Any? {
return if (stringValue != null) {
try {
val gson = Gson()
gson.fromJson<Any>(stringValue, clazz)
}
catch (exception: Exception) {
// yes, we are swallowing the possible
// java.lang.IllegalStateException
null
}
}
else {
null
}
}
Calling this function and attempting to populate the following class:
data class LoggedUser(
@SerializedName("id") val id: Long,
@SerializedName("name") val name: String,
@SerializedName("first_name") val firstName: String,
@SerializedName("last_name") val lastName: String,
@SerializedName("email") val email: String
)
It executes but LoggedUser values are empty (null).
The stringValue is currently:
{"nameValuePairs":{"id":"1654488452866661","name":"Bob Smith","email":"[email protected]","first_name":"Bob","last_name":"Smith"}}
I even tried using a hardcoded class value like this:
gson.fromJson(stringValue, LoggedUser::class.java)
but there was no joy. The stringValue is what gson.toJson(value) generated where value was a JSONObject.
Anybody have an idea what my disconnect is?
Upvotes: 1
Views: 2406
Reputation: 1857
Create a wrapper class
data class LoggedUserWrapper{
@SerializedName("nameValuePairs") val nameValuePairs: LoggedUser
}
and execute
val loggedUser = convertStringToObject(yourJsonString, LoggedUserWrapper::class.java)
This will help you.
Upvotes: 2
Reputation: 3952
Your JSON string actually has two JSON objects, the outer value (which has a key called nameValuePairs
) and the value you actually want to deserialize (which is the value at key nameValuePairs
). You need to dive one level deeper, either through an outer wrapper class which holds your User object or by manually getting the JsonObject at key nameValuePairs
as a String and then passing that to Gson. If the string was just {"id":"1654488452866661","name":"Bob Smith","email":"[email protected]","first_name":"Bob","last_name":"Smith"}
it would deserialize fine.
Upvotes: 2