我从一个服务接收到一个相当深的JSON对象字符串,我必须解析为JSON对象,然后将其映射到类。

如何将JSON字符串转换为Kotlin对象?

在映射到各自的类之后,我使用了来自Jackson的StdDeserializer。当对象的属性也必须被反序列化为类时,问题就出现了。我无法在另一个反序列化器中获得对象映射器,至少我不知道如何获得。

最好是,在本地,我试图减少我需要的依赖项的数量,所以如果答案只是JSON操作和解析它就足够了。


当前回答

你可以使用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
}

科特林豆

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)

其他回答

没有外部库(Android)

解析如下:

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)

首先。

你可以使用JSON到Kotlin数据类转换插件在Android Studio JSON映射到POJO类(Kotlin数据类)。 这个插件将根据JSON注释你的Kotlin数据类。

然后可以使用GSON转换器将JSON转换为Kotlin。

遵循这个完整的教程: Kotlin Android JSON解析教程

如果你想手动解析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"))
}

这使用kotlinx。像以利沙的回答。与此同时,该项目已经过了1.0版本,因此API已经发生了变化。注意,例如JSON。parse被重命名为Json.decodeFromString。此外,从Kotlin 1.4.0开始,它以不同的方式导入gradle:

dependencies {
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.0"
}
apply plugin: 'kotlinx-serialization'

使用示例:

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
@Serializable
data class Point(val x: Int, val y: Int)

val pt = Json.decodeFromString<Point>("""{"y": 1, "x": 2}""")
val str = Json.encodeToString(pt)  // type can be inferred!

val ilist = Json.decodeFromString<List<Int>>("[-1, -2]")
val ptlist = Json.decodeFromString<List<Point>>(
    """[{"x": 3, "y": 4}, {"x": 5, "y": 6}]"""
)

你可以对可空字段和可选字段使用可空类型(T?):

@Serializable
data class Point2(val x: Int, val y: Int? = null)

val nlist = Json.decodeFromString<List<Point2>>(
    """[{"x": 7}, {"x": 8, "y": null}, {"x": 9, "y": 0}]"""
)

Kotlin的数据类是一个主要保存数据的类,并具有自动定义的成员. tostring()和其他方法(例如解构声明)。

似乎Kotlin没有任何内置方法,因为在许多情况下,它只是从Java中导入并实现了一些工具。在尝试了许多包之后,最终这个包运行正常。这个fastjson来自阿里巴巴,非常容易使用。内部构建gradle依赖:

implementation 'com.alibaba:fastjson:1.1.67.android'

在你的Kotlin代码中:

import com.alibaba.fastjson.JSON
var jsonDecodedMap: Map<String, String> =
            JSON.parse(yourStringValueHere) as Map<String, String>;

芬兰湾的科特林序列化

Kotlin特定的库由JetBrains支持的所有平台- Android, JVM, JavaScript,本机。

https://github.com/Kotlin/kotlinx.serialization

Moshi

Moshi是一个JSON库,适用于Android和Java。

https://github.com/square/moshi

杰克逊

https://github.com/FasterXML/jackson

Gson

最受欢迎但几乎被弃用。

https://github.com/google/gson

JSON到Java

http://www.jsonschema2pojo.org/

JSON到Kotlin

智能插件 – https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass-