Last active
May 2, 2024 10:03
-
-
Save wilinz/4bb26bf5b23e0caa80ce0cbbd7d1312d to your computer and use it in GitHub Desktop.
MoshiExt.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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