Skip to content

Instantly share code, notes, and snippets.

@wilinz
Last active May 2, 2024 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilinz/4bb26bf5b23e0caa80ce0cbbd7d1312d to your computer and use it in GitHub Desktop.
Save wilinz/4bb26bf5b23e0caa80ce0cbbd7d1312d to your computer and use it in GitHub Desktop.
MoshiExt.kt
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import okio.BufferedSink
import okio.BufferedSource
inline fun <reified T> Moshi.adapter(): JsonAdapter<T> = adapter(T::class.java)
package com.wilinz.cgsdk.util
import com.squareup.moshi.*
import okio.BufferedSink
import okio.BufferedSource
import java.lang.reflect.Type
inline fun <reified T> Moshi.adapter(): JsonAdapter<T> = adapter(T::class.java)
inline fun <reified T> Moshi.toJson(v: T, type: Type? = null): String {
val actualType = type ?: Types.newParameterizedType(T::class.java)
val jsonAdapter = adapter<T>(actualType)
return jsonAdapter.toJson(v)
}
inline fun <reified T> Moshi.toJson(sink: BufferedSink, v: T, type: Type? = null) {
val actualType = type ?: Types.newParameterizedType(T::class.java)
val jsonAdapter = adapter<T>(actualType)
jsonAdapter.toJson(sink, v)
}
inline fun <reified T> Moshi.toJson(writer: JsonWriter, v: T, type: Type? = null) {
val actualType = type ?: Types.newParameterizedType(T::class.java)
val jsonAdapter = adapter<T>(actualType)
jsonAdapter.toJson(writer, v)
}
inline fun <reified T> Moshi.fromJson(json: String, type: Type? = null): T? {
val actualType = type ?: Types.newParameterizedType(T::class.java)
val jsonAdapter = adapter<T>(actualType)
return jsonAdapter.fromJson(json)
}
inline fun <reified T> Moshi.fromJson(json: BufferedSource, type: Type? = null): T? {
val actualType = type ?: Types.newParameterizedType(T::class.java)
val jsonAdapter = adapter<T>(actualType)
return jsonAdapter.fromJson(json)
}
inline fun <reified T> Moshi.fromJson(json: JsonReader, type: Type? = null): T? {
val actualType = type ?: Types.newParameterizedType(T::class.java)
val jsonAdapter = adapter<T>(actualType)
return jsonAdapter.fromJson(json)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment