MoshiUtils Moshi parsing json Moshi parsing tool class

Use kotlin annotation plugin

apply plugin: 'kotlin-kapt'

Add dependency:

    //Kotlin-Reflect包2.5m,实在太大,这里使用注解的方式
    //implementation 'com.squareup.moshi:moshi-kotlin:1.9.3'
    kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.9.3'
    implementation 'com.squareup.moshi:moshi:1.9.3'

After encapsulation, it can be called by one line of code:

json转对象:
val json = """["1","2","3","4"]"""
val list = json.fromJson<List<String>>()

对象转json
val json = list.toJson()

 

Using Kotlin's inline functions can greatly reduce the code and reduce some unnecessary parameters. For example, it is not necessary to pass class, type, etc.

import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonReader
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import com.squareup.moshi.internal.Util
import okio.Buffer
import okio.BufferedSource
import java.io.InputStream
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 * Created by jingzz on 2020/7/13.
 */

object MoshiUtils {
    val moshiBuild = Moshi.Builder().build()
    //使用Kotlin-Reflect包时,这里改一下:
    //val moshiBuild = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()


    //普通序列化
    fun <T> fromJson(json: String, type: Type): T? = getAdapter<T>(type).fromJson(json)
    fun <T> fromJons(buffer: BufferedSource, type: Type): T? = getAdapter<T>(type).fromJson(buffer)
    fun <T> fromJons(`is`: InputStream, type: Type): T? = getAdapter<T>(type).fromJson(Buffer().readFrom(`is`))
    fun <T> fromJons(reader: JsonReader, type: Type): T? = getAdapter<T>(type).fromJson(reader)

    //自动获取type序列化,性能较差
    inline fun <reified T:Any> fromJson(json: String): T? = getAdapter<T>().fromJson(json)
    inline fun <reified T> fromJson(buffer: BufferedSource): T? = getAdapter<T>().fromJson(buffer)
    inline fun <reified T> fromJson(`is`: InputStream): T? = getAdapter<T>().fromJson(Buffer().readFrom(`is`))
    inline fun <reified T> fromJson(reader: JsonReader): T? = getAdapter<T>().fromJson(reader)

    //高效序列化为list
    inline fun <reified T> listFromJson(json: String): MutableList<T> =
        fromJson(json, Types.newParameterizedType(MutableList::class.java, T::class.java))
            ?: mutableListOf()

    inline fun <reified T> listFromJson(buffer: BufferedSource): MutableList<T> =
        fromJons(buffer, Types.newParameterizedType(MutableList::class.java, T::class.java))
            ?: mutableListOf()

    inline fun <reified T> listFromJson(`is`: InputStream): MutableList<T> =
        fromJons(`is`, Types.newParameterizedType(MutableList::class.java, T::class.java))
            ?: mutableListOf()

    inline fun <reified T> listFromJson(reader: JsonReader): MutableList<T> =
        fromJons(reader, Types.newParameterizedType(MutableList::class.java, T::class.java))
            ?: mutableListOf()


    //高效序列化为map
    inline fun <reified K, reified V> mapFromJson(json: String): MutableMap<K, V> = fromJson(
        json,
        Types.newParameterizedType(MutableMap::class.java, K::class.java, V::class.java)
    ) ?: mutableMapOf()

    inline fun <reified K, reified V> mapFromJson(buffer: BufferedSource): MutableMap<K, V> =
        fromJons(
            buffer,
            Types.newParameterizedType(MutableMap::class.java, K::class.java, V::class.java)
        )?: mutableMapOf()

    inline fun <reified K, reified V> mapFromJson(`is`: InputStream): MutableMap<K, V> = fromJons(
        `is`,
        Types.newParameterizedType(MutableMap::class.java, K::class.java, V::class.java)
    )?: mutableMapOf()

    inline fun <reified K, reified V> mapFromJson(reader: JsonReader): MutableMap<K, V> = fromJons(
        reader,
        Types.newParameterizedType(MutableMap::class.java, K::class.java, V::class.java)
    )?: mutableMapOf()
    //反序列化
    inline fun <reified T> toJson(t: T) = getAdapter<T>().toJson(t) ?: ""

    fun <T> getAdapter(type: Type): JsonAdapter<T> = moshiBuild.adapter(type)
    inline fun <reified T> getAdapter(): JsonAdapter<T> =  moshiBuild.adapter(object :TypeToken<T>(){}.type)

}

abstract class TypeToken<T>{
    val type:Type get() = run{
        val superclass = javaClass.genericSuperclass
        Util.canonicalize((superclass as ParameterizedType).actualTypeArguments[0])
    }
}


//快捷序列化
inline fun <reified T:Any>String.fromJson() = MoshiUtils.fromJson<T>(this)
//快捷反序列化
fun Any.toJson() = MoshiUtils.toJson(this)

Instructions:

//实体类
@JsonClass(generateAdapter = true)
data class Person(val name: String = "Carlson", val age: Int? = 0)

//json
{"name":"Carlson","age":56}

Entity class and json conversion 

        //实体类转json
        val person = Person("Carlson",56)
        val json = person.toJson()

        //json转实体类
        val json = """{"name":"Carlson","age":56}"""
        val person = json.fromJson<Person>()

json to list

        
        val listJson = """[{"name":"Carlson","age":56},{"name":"Carlson","age":56},{"name":"Carlson","age":56}]"""

        //三种方法都可以
        val list1 = listJson.fromJson<List<Person>>()
        val list2 = MoshiUtils.fromJson<List<Person>>(listJson,Types.newParameterizedType(List::class.java,Person::class.java))
        val list3 = MoshiUtils.listFromJson<Person>(listJson)

        //list转json
        val json = list?.toJson()

 

 

Guess you like

Origin blog.csdn.net/jingzz1/article/details/107315110