Java 如何在 Kotlin 中解析 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41928803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to parse JSON in Kotlin?
提问by AJ_1310
I'm receiving a quite deep JSON object string from a service which I must parse to a JSON object and then map it to classes.
我从服务接收到一个非常深的 JSON 对象字符串,我必须将其解析为 JSON 对象,然后将其映射到类。
How can I transform a JSON string to object in Kotlin?
如何在 Kotlin 中将 JSON 字符串转换为对象?
After that the mapping to the respective classes, I was using StdDeserializer from Hymanson. The problem arises at the moment the object had properties that also had to be deserialized into classes. I was not able to get the object mapper, at least I didn't know how, inside another deserializer.
在映射到相应类之后,我使用了 Hymanson 的 StdDeserializer。问题出现在对象具有也必须反序列化为类的属性时。我无法在另一个反序列化器中获得对象映射器,至少我不知道如何获得。
Thanks in advance for any help. Preferably, natively, I'm trying to reduce the number of dependencies I need so if the answer is only for JSON manipulation and parsing it'd be enough.
在此先感谢您的帮助。最好,在本机上,我试图减少我需要的依赖项的数量,所以如果答案仅用于 JSON 操作和解析就足够了。
采纳答案by Istiak Morsalin
You can use this library https://github.com/cbeust/klaxon
你可以使用这个库 https://github.com/cbeust/klaxon
Klaxon is a lightweight library to parse JSON in Kotlin.
Klaxon 是一个在 Kotlin 中解析 JSON 的轻量级库。
回答by markB
Not sure if this is what you need but this is how I did it.
不确定这是否是您需要的,但这就是我所做的。
Using import org.json.JSONObject :
使用 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
}
Here's a sample of the json : { "Foods": { "FoodName": "Apples", "Weight": "110" } }
这是 json 的示例:{ "Foods": { "FoodName": "Apples", "Weight": "110" } }
回答by Neurf
I personally use the Hymanson module for Kotlin that you can find here: Hymanson-module-kotlin.
我个人在 Kotlin 中使用 Hymanson 模块,你可以在这里找到:Hymanson-module-kotlin。
implementation "com.fasterxml.Hymanson.module:Hymanson-module-kotlin:$version"
As an example, here is the code to parse the JSON of the Path of Exile skilltree which is quite heavy (84k lines when formatted) :
例如,这里是解析流放之路技能树的 JSON 的代码,它很重(格式化时为 84k 行):
Kotlin code:
科特林代码:
package util
import com.fasterxml.Hymanson.databind.DeserializationFeature
import com.fasterxml.Hymanson.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 = HymansonObjectMapper()
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 (not-formatted): http://filebin.ca/3B3reNQf3KXJ/rawSkilltree.json
JSON(未格式化):http: //filebin.ca/3B3reNQf3KXJ/rawSkilltree.json
Given your description, I believe it matches your needs.
根据您的描述,我相信它符合您的需求。
回答by Deepshikha Puri
Download the source of deme from here(Json parsing in android kotlin)
从这里下载 deme 的源代码(android kotlin 中的 Json 解析)
Add this dependency:
添加此依赖项:
compile 'com.squareup.okhttp3:okhttp:3.8.1'
Call api function:
调用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()
}
})
回答by KeLiuyue
You can use Gson
.
您可以使用Gson
.
Example
例子
Step 1
第1步
Add compile
添加编译
compile 'com.google.code.gson:gson:2.8.2'
Step 2
第2步
Convert json to Kotlin Bean
(use JsonToKotlinClass)
将 json 转换为Kotlin Bean
(使用JsonToKotlinClass)
Like this
像这样
Json
data
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
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
)
}
Step 3
第 3 步
Use Gson
用 Gson
var gson = Gson()
var mMineUserEntity = gson?.fromJson(response, MineUserEntity.MineUserInfo::class.java)
回答by Elisha Sterngold
There is no question that the future of parsing in Kotlin will be with kotlinx.serialization. It is part of Kotlin libraries. It is still at the time of writing in incubator stage.
毫无疑问,Kotlin 中解析的未来将是 kotlinx.serialization。它是 Kotlin 库的一部分。它仍处于孵化器阶段。
https://github.com/Kotlin/kotlinx.serialization
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")
}
回答by Developine
First of all.
首先。
You can use JSON to Kotlin Data class converter plugin in Android Studio for JSON mapping to POJO classes (kotlin data class). This plugin will annotate your Kotlin data class according to JSON.
您可以使用 Android Studio 中的 JSON 到 Kotlin 数据类转换器插件来将 JSON 映射到 POJO 类(kotlin 数据类)。该插件将根据 JSON 注释您的 Kotlin 数据类。
Then you can use GSON converter to convert JSON to Kotlin.
然后您可以使用 GSON 转换器将 JSON 转换为 Kotlin。
Follow this Complete tutorial: Kotlin Android JSON Parsing Tutorial
按照这个完整的教程: Kotlin Android JSON 解析教程
If you want to parse json manually.
如果你想手动解析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"
}]
"""
Code to Parse above JSON Array and its object at index 0.
在 JSON 数组及其索引 0 处的对象上方解析的代码。
var jsonArray = JSONArray(sampleJson)
for (jsonIndex in 0..(jsonArray.length() - 1)) {
Log.d("JSON", jsonArray.getJSONObject(jsonIndex).getString("title"))
}
回答by frouo
Without external library (on Android)
没有外部库(在 Android 上)
To parse this:
要解析这个:
val jsonString = """
{
"type":"Foo",
"data":[
{
"id":1,
"title":"Hello"
},
{
"id":2,
"title":"World"
}
]
}
"""
Use these classes:
使用这些类:
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")
}
Usage:
用法:
val foos = Response(jsonString)
回答by kundan kamal
http://www.jsonschema2pojo.org/Hi you can use this website to convert json to pojo.
control+Alt+shift+k
http://www.jsonschema2pojo.org/您好,您可以使用此网站将 json 转换为 pojo。
control+Alt+shift+k
After that you can manualy convert that model class to kotlin model class. with the help of above shortcut.
之后,您可以手动将该模型类转换为 kotlin 模型类。借助上述快捷方式。
回答by Facundo Garcia
A bit late, but whatever.
有点晚了,但无论如何。
If you prefer parse JSON to JavaScript like constructs making use of Kotlin semantics, I recommend JSONKraken, of which I am the author.
如果您更喜欢使用 Kotlin 语义将 JSON 解析为 JavaScript 之类的构造,我推荐JSONKraken,我是它的作者。
Suggestions and opinions on the matter are much apreciated!
对此事的建议和意见非常感谢!