Issue
What's the most efficient way to convert a JSON in the format of Map<String, Any>
to the corresponding java/kotlin object?
For now I have to use it like that which seems like a stupid implementation.
gson.fromJson(gson.toJson(mapToConvert), typeToken)
Any suggestions?
Solution
You can use a JsonElement
:
val jsonElement = gson.toJsonTree(map)
val foo = gson.fromJson(jsonElement, Foo::class.java)
You can make this look nicer with a utility function:
inline fun <reified T : Any> Gson.fromMap(map: Map<*, *>) {
return fromJson(toJsonTree(map), T::class.java)
}
Then you can call it like this:
gson.fromMap<Foo>(map)
Answered By - Salem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.