json - 解析单个 JSON 元素时出现问题 (Swift)

标签 json swift alamofire swifty-json

我的 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!)
    }
}

最佳答案

外部两个对象是字典,内部对象是数组。

试试这个,它遍历内部数组并打印属性 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 - 解析单个 JSON 元素时出现问题 (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31167891/

相关文章:

c# - 如何使用 WinRT 将 json 发布到网站?

ios - 如何在 Swift 中创建像 Alamofire 那样的 API?

php - FatalThrowableError 对 laravel 5.5 API 请求的 null 调用成员函数 where()

php - 第二张表的响应相同

ios - Swift - 找不到 jonkykong SideMenu UISideMenuNavigationController

swift - 如何为字典的键添加额外的值?

ios - Swift IOS 13,IAP - "Cannot connect to Itunes Connect"

ios - 字符 0 周围的 Alamofire 无效值

ios - 解码错误 : The data couldn't be read. Alamofire

javascript - 你能以 UTF-16 格式传输数据吗?