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

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

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

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


当前回答

芬兰湾的科特林序列化

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-

其他回答

如果您更喜欢解析JSON而不是使用Kotlin语法解析类似javascript的结构,那么我推荐JSONKraken,我是它的作者。

你可以这样做:

val json: JsonValue = JsonKraken.deserialize("""{"getting":{"started":"Hello World"}}""")
println(JsonKraken.serialize(json)) //prints: {"getting":{"started":"Hello World"}}
println(json["getting"]["started"].cast<String>()) //prints: Hello World

对此事的建议和意见,非常感谢!

您可以使用这个库https://github.com/cbeust/klaxon

Klaxon是一个轻量级库,用于在Kotlin中解析JSON。

芬兰湾的科特林序列化

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-

首先。

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

不知道这是不是你需要的但我就是这么做的。

使用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的示例:

{“食品”: [{“食品名称”: “苹果”,“重量”: “110” } ]}