利用Gson将json转换为Map集合

转载请注明:https://blog.csdn.net/u012854870/article/details/97655914

json数据格式:

{
	"areacode": [{
			"code": "0086",
			"name": "+86"
		},
		{
			"code": "00852",
			"name": "+852"
		}
	],
	"城市": [{
		"code": "上海",
		"name": "shanghia"
	}]
}

第一种:直接转换为Map集合

 fun jsonToMap(jsonString: String) {
        val gson = Gson()
        //利用Gson,无Bean类json转Map
        val map = gson.fromJson<Map<String, Any>>(jsonString, Map::class.java)
        //获取Map中的数据
        val data = map["areacode"] as MutableList<*>
        val dictionaryItem = data[0] as Map<*, *>
        println(map)
        println(data)
        println(dictionaryItem)
        println(dictionaryItem["code"])

    }

第二种:转换为Map和具体的对象实例

//对象类
data class DictionaryItem(
    var code: String,
    var name: String
)

//转化实现方法
  fun jsonToMapBean(jsonString: String) {
        val gson = Gson()
        val type = object : TypeToken<Map<String, MutableList<DictionaryItem>>>() {}.type
        val map = gson.fromJson<Map<String, MutableList<DictionaryItem>>>(jsonString, type)
        //获取Map中的数据
        val data = map["areacode"]
        val dictionaryItem = data?.get(0)
        println(map)
        println(data)
        println(dictionaryItem)
        println(dictionaryItem?.code)

    }

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页