5

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?

Martin Mlostek
  • 2,755
  • 1
  • 28
  • 57

1 Answers1

8

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)
X09
  • 3,827
  • 10
  • 47
  • 92
Salem
  • 13,516
  • 4
  • 51
  • 70
  • well, thats just the same thing, my goal is to avoid that one extra gson conversion – Martin Mlostek Dec 20 '17 at 10:58
  • @martynmlostekk No, it is not, `toJson` converts it to a string. `toJsonTree` converts it into an in-memory representation of a JSON element tree ([`JsonElement`](https://google.github.io/gson/apidocs/com/google/gson/JsonElement.html)). I see what you mean though and I do not think Gson has a mechanism to do this. [This is more directly possible with Jackson though](https://stackoverflow.com/a/16430704/7366707). – Salem Dec 20 '17 at 11:00
  • okay, thats not exactly what i need but in this case (using with retrofit) i can at least reduce it by the gson conversions by 1 (to a total of 2). thanks. will mark it as solution if nobody else will answer within couple of days – Martin Mlostek Dec 20 '17 at 15:43