【问题标题】:How do I parse empty dictionary JSON in Swift?如何在 Swift 中解析空字典 JSON?
【发布时间】:2017-03-17 19:54:56
【问题描述】:

我正在使用 swift 解析 JSON。我来到一本返回空的字典。我将如何将其解析为自定义对象?

** 我在看Image**

},
        "name": "Al bake",
        "image": {},
        "website": "",
        "category": {
            "id": "d59d2b1c-ca37-4c76-bb93-1c0ba967ee84",
            "name": "Test Category",
            "slug": "test-category",
            "is_active": true
        },

【问题讨论】:

  • 为什么需要解析它?
  • 我只是想学习如何做到这一点=]
  • 你的image key只是一个空字典,你问的是如何解析json数据?
  • 正确。我将如何为它创建一个结构或类?像自定义对象?

标签: json swift parsing


【解决方案1】:

如果您需要image 的值,它应该是一个字典(空或包含键和值),您需要知道包含它的类型。

例如,假设以下代码包含在字典中:

"name": "Al bake",
"image": {},
"website": "",
"category": {
    "id": "d59d2b1c-ca37-4c76-bb93-1c0ba967ee84",
    "name": "Test Category",
    "slug": "test-category",
    "is_active": true

你会这样做:

if let image = dictionary["image"] as? Dictionary<String, Any> {
    print(image.description)
} else {
    print("Image does not contain a value")
}

【讨论】:

  • 我想将它设置为null 什么?
  • 您是要从整个 JSON 数据结构中创建自定义对象,还是只想检索 image 键的值?
  • 为图片创建自定义对象
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多