FastJson解析封装

857 阅读1分钟

导包

implementation 'com.alibaba:fastjson:1.2.48'

方法

//FastKtx方法
toAny		:json 转任意类
toMap		:json 转 Map
toList		: json 转 List
toJson		: 任意类转 json
//扩展函数
toAny		:json 转任意类
toMap		:json 转 Map
toList		: json 转 List
toJson		: 任意类转 json

注意事项

使用时涉及到泛型相关,泛型 T 要转的类必须要有无参构造方法,一般 Java 默认就有,如果使用 Kotlin 就需要注意了,设置默认值是无效的,下面这种才有效:

class TestJ constructor(){
    var name: String? = null
    var isSuccess = false
}

封装类

//json -> any
inline fun <reified T> String?.toAny() = FastKtx.toAny<T>(this)
fun <T> String?.toAny(tClass: Class<T>?) = FastKtx.toAny(this, tClass)

//json -> map
fun <T> String?.toMap() = FastKtx.toMap<Map<String, T>>(this)

//json -> list
inline fun <reified T> String?.toList() = FastKtx.toList<T>(this)
fun <T> String?.toList(tClass: Class<T>?) = FastKtx.toList(this, tClass)

//any -> json
fun Any?.toJson() = FastKtx.toJson(this)

object FastKtx {
    /**
     *json  ----->  T
     * @param T
     * @param json
     * @param tClass
     * @return
     */
    inline fun <reified T> toAny(json: String?): T? {
        return toAny(json, T::class.java)
    }

    fun <T> toAny(json: String?, tClass: Class<T>?): T? {
        if (json.isNullOrEmpty()) return null
        return try {
            JSON.parseObject(json, tClass)
        } catch (e: Exception) {
            null
        }
    }

    /**
     *json ---->  map
     * @param T
     * @param json
     * @return
     */
    fun <T> toMap(json: String?): Map<String, T>? {
        if (json.isNullOrEmpty()) return null
        try {
            return JSON.parseObject<Map<String, T>>(json, MutableMap::class.java)
        } catch (e: Exception) {
        }
        return null
    }

    /**
     *json ----->  list
     * @param T
     * @param json
     * @param tClass
     * @return
     */
    inline fun <reified T> toList(json: String?): List<T>? {
        return toList(json, T::class.java)
    }

    fun <T> toList(json: String?, tClass: Class<T>?): List<T>? {
        if (json.isNullOrEmpty()) return null
        return try {
            JSON.parseArray(json, tClass)
        } catch (e: Exception) {
            null
        }
    }

    /**
     *any -----> json
     * @param any
     * @return
     */
    fun toJson(any: Any?): String? {
        return try {
            JSON.toJSONString(any)
        } catch (e: Exception) {
            null
        }
    }
}