我从服务中收到一个非常深的JSON对象字符串,我必须将其解析为JSON对象,然后将其映射到类。
如何在Kotlin中将JSON字符串转换为对象?
在那之后映射到各个类,我使用了Jackson的StdDeserializer。问题出现在对象具有也必须被反序列化为类的属性的时刻。我无法在另一个反序列化器中获取对象映射器,至少我不知道如何。
在此先感谢您的帮助。优选地,本机地,我正在尝试减少我需要的依赖项的数量,因此如果答案仅用于JSON操作并且解析它就足够了。
你可以使用这个库https://github.com/cbeust/klaxon
Klaxon是一个轻量级的库,用于在Kotlin中解析JSON。
从这里下载deme的来源(Json parsing in android kotlin)
添加此依赖项:
compile 'com.squareup.okhttp3:okhttp:3.8.1'
调用api函数:
fun run(url: String) {
dialog.show()
val request = Request.Builder()
.url(url)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
dialog.dismiss()
}
override fun onResponse(call: Call, response: Response) {
var str_response = response.body()!!.string()
val json_contact:JSONObject = JSONObject(str_response)
var jsonarray_contacts:JSONArray= json_contact.getJSONArray("contacts")
var i:Int = 0
var size:Int = jsonarray_contacts.length()
al_details= ArrayList();
for (i in 0.. size-1) {
var json_objectdetail:JSONObject=jsonarray_contacts.getJSONObject(i)
var model:Model= Model();
model.id=json_objectdetail.getString("id")
model.name=json_objectdetail.getString("name")
model.email=json_objectdetail.getString("email")
model.address=json_objectdetail.getString("address")
model.gender=json_objectdetail.getString("gender")
al_details.add(model)
}
runOnUiThread {
//stuff that updates ui
val obj_adapter : CustomAdapter
obj_adapter = CustomAdapter(applicationContext,al_details)
lv_details.adapter=obj_adapter
}
dialog.dismiss()
}
})
毫无疑问,在Kotlin中解析的未来将与kotlinx.serialization一起使用。它是Kotlin图书馆的一部分。它还处于孵化阶段的写作阶段。
https://github.com/Kotlin/kotlinx.serialization
import kotlinx.serialization.*
import kotlinx.serialization.json.JSON
@Serializable
data class MyModel(val a: Int, @Optional val b: String = "42")
fun main(args: Array<String>) {
// serializing objects
val jsonData = JSON.stringify(MyModel.serializer(), MyModel(42))
println(jsonData) // {"a": 42, "b": "42"}
// serializing lists
val jsonList = JSON.stringify(MyModel.serializer().list, listOf(MyModel(42)))
println(jsonList) // [{"a": 42, "b": "42"}]
// parsing data back
val obj = JSON.parse(MyModel.serializer(), """{"a":42}""")
println(obj) // MyModel(a=42, b="42")
}
解析这个:
val jsonString = """
{
"type":"Foo",
"data":[
{
"id":1,
"title":"Hello"
},
{
"id":2,
"title":"World"
}
]
}
"""
使用这些类:
import org.json.JSONObject
class Response(json: String) : JSONObject(json) {
val type: String? = this.optString("type")
val data = this.optJSONArray("data")
?.let { 0.until(it.length()).map { i -> it.optJSONObject(i) } } // returns an array of JSONObject
?.map { Foo(it.toString()) } // transforms each JSONObject of the array into Foo
}
class Foo(json: String) : JSONObject(json) {
val id = this.optInt("id")
val title: String? = this.optString("title")
}
用法:
val foos = Response(jsonString)
不确定这是否是你需要的,但这就是我做的。
使用import org.json.JSONObject:
val jsonObj = JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1))
val foodJson = jsonObj.getJSONArray("Foods")
for (i in 0..foodJson!!.length() - 1) {
val categories = FoodCategoryObject()
val name = foodJson.getJSONObject(i).getString("FoodName")
categories.name = name
}
以下是json的样本:{“Foods”:{“FoodName”:“Apples”,“Weight”:“110”}}
你可以使用Gson
。
步骤1
添加编译
compile 'com.google.code.gson:gson:2.8.2'
第2步
将json转换为Kotlin Bean
(使用JsonToKotlinClass)
像这样
Json
数据
{
"timestamp": "2018-02-13 15:45:45",
"code": "OK",
"message": "user info",
"path": "/user/info",
"data": {
"userId": 8,
"avatar": "/uploads/image/20180115/1516009286213053126.jpeg",
"nickname": "",
"gender": 0,
"birthday": 1525968000000,
"age": 0,
"province": "",
"city": "",
"district": "",
"workStatus": "Student",
"userType": 0
},
"errorDetail": null
}
Kotlin Bean
class MineUserEntity {
data class MineUserInfo(
val timestamp: String,
val code: String,
val message: String,
val path: String,
val data: Data,
val errorDetail: Any
)
data class Data(
val userId: Int,
val avatar: String,
val nickname: String,
val gender: Int,
val birthday: Long,
val age: Int,
val province: String,
val city: String,
val district: String,
val workStatus: String,
val userType: Int
)
}
第3步
使用Gson
var gson = Gson()
var mMineUserEntity = gson?.fromJson(response, MineUserEntity.MineUserInfo::class.java)
我个人使用Jackson模块进行Kotlin,你可以在这里找到:jackson-module-kotlin。
implementation "com.fasterxml.jackson.module:jackson-module-kotlin:$version"
作为一个例子,这里是解析流亡之路技能树的JSON的代码,它非常重(格式化时为84k行):
Kotlin代码:
package util
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.module.kotlin.*
import java.io.File
data class SkillTreeData( val characterData: Map<String, CharacterData>, val groups: Map<String, Group>, val root: Root,
val nodes: List<Node>, val extraImages: Map<String, ExtraImage>, val min_x: Double,
val min_y: Double, val max_x: Double, val max_y: Double,
val assets: Map<String, Map<String, String>>, val constants: Constants, val imageRoot: String,
val skillSprites: SkillSprites, val imageZoomLevels: List<Int> )
data class CharacterData( val base_str: Int, val base_dex: Int, val base_int: Int )
data class Group( val x: Double, val y: Double, val oo: Map<String, Boolean>?, val n: List<Int> )
data class Root( val g: Int, val o: Int, val oidx: Int, val sa: Int, val da: Int, val ia: Int, val out: List<Int> )
data class Node( val id: Int, val icon: String, val ks: Boolean, val not: Boolean, val dn: String, val m: Boolean,
val isJewelSocket: Boolean, val isMultipleChoice: Boolean, val isMultipleChoiceOption: Boolean,
val passivePointsGranted: Int, val flavourText: List<String>?, val ascendancyName: String?,
val isAscendancyStart: Boolean?, val reminderText: List<String>?, val spc: List<Int>, val sd: List<String>,
val g: Int, val o: Int, val oidx: Int, val sa: Int, val da: Int, val ia: Int, val out: List<Int> )
data class ExtraImage( val x: Double, val y: Double, val image: String )
data class Constants( val classes: Map<String, Int>, val characterAttributes: Map<String, Int>,
val PSSCentreInnerRadius: Int )
data class SubSpriteCoords( val x: Int, val y: Int, val w: Int, val h: Int )
data class Sprite( val filename: String, val coords: Map<String, SubSpriteCoords> )
data class SkillSprites( val normalActive: List<Sprite>, val notableActive: List<Sprite>,
val keystoneActive: List<Sprite>, val normalInactive: List<Sprite>,
val notableInactive: List<Sprite>, val keystoneInactive: List<Sprite>,
val mastery: List<Sprite> )
private fun convert( jsonFile: File ) {
val mapper = jacksonObjectMapper()
mapper.configure( DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true )
val skillTreeData = mapper.readValue<SkillTreeData>( jsonFile )
println("Conversion finished !")
}
fun main( args : Array<String> ) {
val jsonFile: File = File( """rawSkilltree.json""" )
convert( jsonFile )
JSON(未格式化):http://filebin.ca/3B3reNQf3KXJ/rawSkilltree.json
鉴于您的描述,我相信它符合您的需求。
首先。
您可以将JSON用于Android Studio中的Kotlin Data类转换器插件,以便将JSON映射到POJO类(kotlin数据类)。该插件将根据JSON注释您的Kotlin数据类。
然后你可以使用GSON转换器将JSON转换为Kotlin。
按照完整的教程:Kotlin Android JSON Parsing Tutorial
如果要手动解析json。
val **sampleJson** = """
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio
reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita"
}]
"""
要在JSON数组上解析的代码及其在索引0处的对象。
var jsonArray = JSONArray(sampleJson)
for (jsonIndex in 0..(jsonArray.length() - 1)) {
Log.d("JSON", jsonArray.getJSONObject(jsonIndex).getString("title"))
}
要将JSON转换为Kotlin,请使用http://www.json2kotlin.com/
您也可以使用Android Studio插件。文件>设置,在左侧树中选择Plugins
,按“浏览存储库...”,搜索“JsonToKotlinClass”,选择它并单击绿色按钮“安装”。
AS重启后,您可以使用它。您可以使用File > New > JSON To Kotlin Class (JsonToKotlinClass)
创建一个类。另一种方法是按Alt + K.
然后,您将看到一个粘贴JSON的对话框。
在2018年,我不得不在课程开始时添加package com.my.package_name
。
http://www.jsonschema2pojo.org/您好,您可以使用此网站将json转换为pojo。 控制+ ALT + SHIFT + K
之后,您可以手动将该模型类转换为kotlin模型类。在上面的快捷方式的帮助下。