不需要先解析成对象,通过JsonElement实现
try {
val jumpJson = "{\"iOS\":{\"module\":\"maintenance\",\"action\":\"pushToMaintenance\"},\"android\":{\"module\":\"appointmentMaintai\",\"action\":\"pushToMaintenance\"}}"
val rootElement = JsonParser.parseString(jumpJson)?.asJsonObject
val androidElement = rootElement?.get("android")?.asJsonObject
val module = androidElement?.get("module")?.asString
val action = androidElement?.get("action")?.asString
if(!module.isMyBlankOrNull() && !action.isMyBlankOrNull()){
println("$module $action")
return
}
}catch (e:Exception){
}
2、json和对象互转
import com.google.gson.Gson
import org.junit.Test
class KTTest {
data class Person(val name:String,val sex:String,val age:Int)
@Test
fun test() {
//对象转json
val json = Gson().toJson(Person("皓娇","女",18))
println(json)
//json转对象
val person = Gson().fromJson(json,Person::class.java)
println(person)
}
}
加一个泛型的扩展方法
fun String.json2Obj(): T {
val typeT = object : TypeToken(){}.type
return Gson().fromJson(this, typeT)
}
这时候你发现是行不通的,报java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to Person,如果想研究其他写法,会更加麻烦,不建议,还是老老实实直接用类转比较好。
3、json和List互转import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.junit.Test
class KTTest {
data class Person(val name: String, val sex: String, val age: Int)
@Test
fun test() {
//list转json
val list = arrayListOf(Person("皓娇1号", "女", 18), Person("皓娇2号", "女", 18))
val json = Gson().toJson(list)
println(json)
//json转list
val newList = Gson().fromJson>(json, object : TypeToken>() {}.type)
println(newList)
}
}
4、json转包含泛型的对象
一般网络回调都会包含泛型的方式,方便统一处理。例如:Response
class GsonTest2 {
@Test
fun test() {
val resp = BaseResponse(200,Person("皓娇","女",18),"成功")
val json = Gson().toJson(resp)
val a = Gson().fromJson>(json,getRespType(Person::class.java))
println(a)
}
}
data class Person(val name: String, val sex: String, val age: Int)
data class BaseResponse(val code:Int,val data:T?,val msg:String)
fun getRespType(clz: Class<*>) = object : ParameterizedType {
override fun getRawType(): Type = BaseResponse::class.java
override fun getActualTypeArguments(): Array = arrayOf(clz)
override fun getOwnerType(): Type? = null
}
如果data是List类型,还要在getActualTypeArguments的值上处理,上才艺:
class GsonTest2 {
@Test
fun test() {
val list = arrayListOf(Person("皓娇1号", "女", 18), Person("皓娇2号", "女", 18))
val resp = BaseResponse(200,list,"成功")
val json = Gson().toJson(resp)
val a = Gson().fromJson>>(json,getRespListType(Person::class.java))
println(a)
}
}
data class Person(val name: String, val sex: String, val age: Int)
data class BaseResponse(val code:Int,val data:T?,val msg:String)
fun getRespListType(clz: Class<*>) = object : ParameterizedType {
override fun getRawType(): Type = BaseResponse::class.java
override fun getActualTypeArguments(): Array = arrayOf(getType(List::class.java, clz))
override fun getOwnerType(): Type? = null
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)