Hello guys, I wanted to use moshi to parse object ...
# android
p
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
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
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
Copy code
inline fun <reified T> Moshi.adapter(): JsonAdapter<T> {
  return adapter(typeOf<T>())
}
👌 1
187 Views