简体   繁体   中英

Gson Map<String, Any> to Object

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM