【问题标题】:Trouble parsing individual JSON elements (Swift)解析单个 JSON 元素时遇到问题 (Swift)
【发布时间】:2015-07-01 17:25:42
【问题描述】:

我的 JSON 结构如下。我对 Alamofire 和 SwiftyJSON 很陌生。在浏览了文档并修改了好几个小时后,我一直无法弄清楚如何解析这个 JSON 结构中的各个元素。

{
  "transactions": {
     "transaction": [
        {
          "payment_id": 2,
          "payment_date": "2015-06-30",
          "url": "myurl",
          "title": "mytitle",
          "sell_id": 4,
          "last_update": "2015-06-30",
          "inventory_id": 4,
          "amount": "30.00",
          "item_id": 4682,
          "buyer_id": 1
        },
        {
          "payment_id": 1,
          "payment_date": "2015-06-29",
          "url": "myurl2",
          "title": "mytitle",
          "sell_id": 3,
          "last_update": "2015-06-29",
          "inventory_id": 3,
          "amount": "40.00",
          "item_id": 1061,
          "buyer_id": 1
        }
     ]
  }
}

代码:

class func RecentTransactions() {
    Alamofire.request(.GET, requestURL)
        .responseJSON { (_, _, jsonData, _) in
            println(jsonData!)
            let json = JSON(jsonData!)
    }
}

【问题讨论】:

标签: json swift alamofire swifty-json


【解决方案1】:

外面的两个对象是字典,里面的对象是一个数组。

试试这个,它遍历内部数组并打印属性titleurl 的值(字典键有点混乱;-))

  class func RecentTransactions() {
    Alamofire.request(.GET, requestURL)
      .responseJSON { (_, _, jsonData, _) in
        println(jsonData!)
        let json = JSON(jsonData!)
        let transactions = json["transactions"]
        let transaction = transactions["transaction"]
        for (index: String, action: JSON) in transaction {
          println(action["title"])
          println(action["url"])
        }
    }
  }

【讨论】:

  • 非常感谢,这有效。是的,它们有点令人困惑,因为我也是 JSON 结构的新手。
猜你喜欢
  • 1970-01-01
  • 2015-03-23
  • 1970-01-01
  • 1970-01-01
  • 2021-03-28
  • 2012-11-12
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
相关资源
最近更新 更多