https://kotlinlang.org logo
#android
Title
# android
p

pawel.rybicki

10/08/2019, 12:28 PM
Hello guys, I wanted to use moshi to parse object to json string, the example on the lib docs says smth like this along the lines in order to achieve that:
Copy code
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<BlackjackHand> jsonAdapter = moshi.adapter(BlackjackHand.class);

String json = jsonAdapter.toJson(blackjackHand);
and I've been thinking its a bit of a boiler plate to write it for each class, so I came up with the idea of this:
fun Any.toJson() = Moshi.Builder().build().adapter(Any::class.java).toJson(this)
this way I can simply call
AnyObj.toJson()
, but I wonder if there is any downside of such solution?
j

jw

10/08/2019, 12:29 PM
You should create the Moshi instance once and reuse it everywhere
You should also ideally only look up the adapters as few times as possible
Also using
Any
as the lookup type is not recommended
p

pawel.rybicki

10/08/2019, 12:32 PM
uhm I see, so smth like this
moshiInstance.adapter(Any::class.java).toJson(this)
would be a little improvement, but using
Any
will slow down parsing object or...?
j

jw

10/08/2019, 1:14 PM
Copy code
inline fun <reified T> Moshi.adapter(): JsonAdapter<T> {
  return adapter(typeOf<T>())
}
👌 1
171 Views