import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
/**
* json字符串 转成 T
*
* 如果解析出现异常则返回null
* @return json字符串对应的bean
*/
inline fun <reified T> String?.fromJson(): T? =
if (this.isNullOrBlank()) null
else try {
Moshi.Builder().add(KotlinJsonAdapterFactory()).build().adapter(T::class.java).fromJson(this)
} catch (e: Throwable) {
e.printStackTrace()
null
}
/**
* json字符串 转成 List<`T`>
*
* 如果解析出现异常则返回null
* @return json字符串对应的bean
*/
inline fun <reified T> String?.fromJsonList(): List<T>? =
if (this.isNullOrBlank()) null
else try {
Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
.adapter<List<T>>(Types.newParameterizedType(List::class.java, T::class.java))
.fromJson(this)
} catch (e: Throwable) {
e.printStackTrace()
null
}
/**
* json字符串 转成 Map<K,V>
*
* 如果解析出现异常则返回null
* @return json字符串对应的bean
*/
inline fun <reified K, reified V> String?.fromJsonMap(): Map<K, V>? =
if (this.isNullOrBlank()) null
else try {
Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
.adapter<Map<K, V>>(Types.newParameterizedType(Map::class.java, K::class.java, V::class.java))
.fromJson(this)
} catch (e: Throwable) {
e.printStackTrace()
null
}
/**
* 将 T 转成 json字符串
*
* 如果转换出现异常则返回null
* @return bean对应json字符串
*/
inline fun <reified T> T?.toJson(): String? =
if (this == null) null
else try {
Moshi.Builder().add(KotlinJsonAdapterFactory()).build().adapter(T::class.java).toJson(this)
} catch (e: Throwable) {
e.printStackTrace()
null
}
/**
* 将 List<`T`> 转成 json字符串
*
* 如果转换出现异常则返回null
* @return bean对应json字符串
*/
inline fun <reified T> List<T>?.toJsonList(): String? =
if (this == null) null
else try {
Moshi.Builder().add(KotlinJsonAdapterFactory()).build().adapter<List<T>>(Types.newParameterizedType(List::class.java, T::class.java))
.toJson(this)
} catch (e: Throwable) {
e.printStackTrace()
null
}
/**
* 将 Map<K,V> 转成 json字符串
*
* 如果转换出现异常则返回null
* @return bean对应json字符串
*/
inline fun <reified K, reified V> Map<K, V>?.toJsonMap(): String? =
if (this == null) null
else try {
Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
.adapter<Map<K, V>>(Types.newParameterizedType(Map::class.java, K::class.java, V::class.java))
.toJson(this)
} catch (e: Throwable) {
e.printStackTrace()
null
}
moshi kotlin 扩展方法
最新推荐文章于 2024-04-11 02:41:26 发布
这个博客介绍了如何使用Kotlin和Moshi库创建一系列实用函数,用于方便地在JSON字符串与Java对象之间进行转换。提供的函数包括将空字符串转化为null、异常处理以及不同类型(如单一对象、列表、映射)的转换方法,适用于Android或服务器端的Kotlin开发者。
摘要由CSDN通过智能技术生成