我不知道如何解析这个嵌套的json

时间:2019-10-07 17:30:38

标签: android json kotlin

我正在尝试使用解析此JSON。但是,我不知道如何解析“孩子”。如何将其映射到课程?

我创建了一个类来解析“ displayProperties”,但是我不知道如何解析“子代”

{
  "displayProperties": {
    "description": "",
    "name": "Les Ténèbres",
    "icon": "/common/destiny2_content/icons/39ba3c78d0ad06c0728374d591c65821.png",
    "hasIcon": true
  },
  "originalIcon": "/common/destiny2_content/icons/39ba3c78d0ad06c0728374d591c65821.png",
  "rootViewIcon": "/common/destiny2_content/icons/39ba3c78d0ad06c0728374d591c65821.png",
  "nodeType": 1,
  "scope": 1,
  "objectiveHash": 4168198558,
  "children": {
    "presentationNodes": [
      {
        "presentationNodeHash": 655926402
      },
      {
        "presentationNodeHash": 2082711113
      },
      {
        "presentationNodeHash": 2474271317
      }
    ],
    "collectibles": [],
    "records": []
  }
}
abstract class DestinyObject(json : String) : JSONObject(json){

    fun optDisplayProperties() : DisplayProperties{
        val json_object : DisplayProperties = this.optJSONObject("displayProperties") as DisplayProperties
        return json_object
    }
}
class DisplayProperties(json : String) : JSONObject(json){
    val name = this.optString("name")
    val icon = this.optString("icon")
    val description = this.optString("description")

}

2 个答案:

答案 0 :(得分:0)

创建您的Model类,如下所示:

class Model(
    val displayProperties: DisplayProperties,
    val originalIcon: String,
    val rootViewIcon: String,
    val nodeType: String,
    val scope: String,
    val objectiveHash: Long,
    val children: Children
)

class Children(
    val presentationNodes: List<Any>,
    val collectibles: List<Any>,
    val records: List<Any>
)

class DisplayProperties(
    val description: String,
    val name: String,
    val icon: String,
    val hasIcon: Boolean
)

如果您要使用其他任何模型代替任何,则还必须创建此模型。希望这会帮助你。除此之外,您还可以使用JSON Parser库(如 GSON )来解析JsonObject。对于上述JSON对象,代码如下:

Gson().fromJson(json, Model::class.java)

答案 1 :(得分:0)

只需在任何Json解析网站上单独过滤每个对象即可使用  Gson().fromJson(json, Model::class.java) 在您的代码中