Guide package
Implementation 'com. Alibaba: fastjson: 1.2.48'Copy the code
methods
//FastKtx toAny: json toAny class toMap: json toMap toList: json toList toJson: ToAny class toJson // extension function toAny: json toAny class toMap: json toMap toList: json toList toJson: any class toJsonCopy the code
Matters needing attention
If you use Kotlin, you need to set the default value of T to a class that has no arguments. If you use Kotlin, you need to set the default value to a class that has no arguments.
class TestJ constructor(){
var name: String? = null
var isSuccess = false
}
Copy the code
Wrapper class
//json -> any
inline fun <reified T>String? .toAny(a) = FastKtx.toAny<T>(this)
fun <T>String? .toAny(tClass: Class<T>? = FastKtx.toAny(this, tClass)
//json -> map
fun <T>String? .toMap(a) = FastKtx.toMap<Map<String, T>>(this)
//json -> list
inline fun <reified T>String? .toList(a) = FastKtx.toList<T>(this)
fun <T>String? .toList(tClass: Class<T>? = FastKtx.toList(this, tClass)
//any -> json
funAny? .toJson(a) = 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}}}Copy the code