【问题标题】:Get key of dictionary on JSON parse with SwiftyJSON使用 SwiftyJSON 获取 JSON 解析的字典键
【发布时间】:2016-12-21 10:55:11
【问题描述】:

我想在这个 JSON 上获取“字典的键”(这就是我所说的,不确定它是否正确)

{
  "People": {
    "People with nice hair": {
      "name": "Peter John",
      "age": 12,
      "books": [
        {
          "title": "Breaking Bad",
          "release": "2011"
        },
        {
          "title": "Twilight",
          "release": "2012"
        },
        {
          "title": "Gone Wild",
          "release": "2013"
        }
      ]
    },
    "People with jacket": {
      "name": "Jason Bourne",
      "age": 15,
      "books": [
        {
          "title": "Breaking Bad",
          "release": "2011"
        },
        {
          "title": "Twilight",
          "release": "2012"
        },
        {
          "title": "Gone Wild",
          "release": "2013"
        }
      ]
    }
  }
}

首先,我已经创建了我的 People 结构,该结构将用于从这些 JSON 进行映射。 这是我的人员结构

struct People {
    var peopleLooks:String?
    var name:String?
    var books = [Book]()
}

这是我的书结构

struct Book {
    var title:String?
    var release:String?
}

从该 JSON 中,我使用 Alamofire 和 SwiftyJSON 创建了引擎,将通过完成处理程序在我的控制器中调用它

Alamofire.request(request).responseJSON { response in
   if response.result.error == nil {
      let json = JSON(response.result.value!)
      success(json)
   }
}

这就是我在控制器中所做的事情

Engine.instance.getPeople(request, success:(JSON?)->void),
   success:{ (json) in

   // getting all the json object
   let jsonRecieve = JSON((json?.dictionaryObject)!)

   // get list of people
   let peoples = jsonRecieve["People"]

   // from here, we try to map people into our struct that I don't know how.
}

我的问题是,如何将我的peoplesjsonRecieve["People"] 映射到我的结构中? 我希望 "People with nice hair" 在我的 People 结构上作为 peopleLooks 的值。我认为"People with nice hair" 是一种字典或其他东西的键,但我不知道如何得到它。

任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: ios swift alamofire swifty-json


    【解决方案1】:

    当你遍历字典时,例如

    for peeps in peoples
    

    您可以使用以下方式访问密钥

    peeps.0
    

    和价值与

    peeps.1
    

    【讨论】:

    • 是啊啊啊,你拯救了我的一天!非常感谢你,@NickCatib!将在几分钟内批准此答案。
    • 非常有帮助:)
    【解决方案2】:

    你可以使用键值循环。

    for (key,subJson):(String, JSON) in json["People"] {
       // you can use key and subJson here.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多