【问题标题】:How to parse multidimension array inside json using SWIFT如何使用 SWIFT 解析 json 中的多维数组
【发布时间】:2015-07-02 04:22:33
【问题描述】:

这是我的示例 JSON 数据

{
    "COD": [ {    
        "Merchant": {       
            "MerchantID": "4701",
            "MerchantCompany": "PAMB",
            "MerchantName": "Phira",
            "MerchantSurname": "Mueadnok",
            "MerchantAddress": "54 MT Mansion",
            "MerchantCity": "Huaykwang",
            "MerchantProvince": "Bangkok",
            "MerchantTel": "0816547412"
        },
        "Order": 
        {    
            "OrderID": "875321",
            "ProductName": "SKII miracle water",
            "ProductPrice": "1020",
            "ProductDimention": "10X10X20 [W*H*D]",
            "ProductWeight": "200G",
            "CollectITEM": "0",
            "Deliver": "0"
        },
        "Customer": 
        {
            "CustomerName": "Malee",
            "CustomerSurname": "",
            "CustomerAddress": "54 MT Mansion",
            "CustomerCity": "Huaykwang",
            "CustomerProvince": "Bangkok",
            "CustomerTel": "0816547412"
        }    
    }]
}     

在 XCode6.3 中

    var endpoint = NSURL(string: /* Link From site */)
    var data = NSData(contentsOfURL: endpoint!)        

    if let json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary {
        if let items = json["COD"] as? NSArray {
            for item in items{
               println(item["Order"])
                println("_______________________________________")
                if let order = item["Order"] as? NSDictionary {
                    for orderDetail in order {

                        println(orderDetail["OrderID"])
                        // i need to present only OrderID
                    }
                }
            }
        }
    }

我使用此代码解析 JSON 数组,但输出仅显示“订单”中的列表,我只需要使用“OrderID”。谁能帮我解决这个问题

【问题讨论】:

  • 'order' 在这种情况下是字典而不是数组。因此您需要将其类型转换为字典而不是数组。
  • 嘿。 thx nshebbar 但仍然无法取出 OrderID
  • 您的 JSON 无效。您在某处缺少结束 ]。

标签: ios json swift multidimensional-array


【解决方案1】:

试试 SwiftyJSON 库

https://github.com/SwiftyJSON/SwiftyJSON

它简化了一切。

猜你喜欢
  • 2014-01-06
  • 2014-02-08
  • 2016-12-14
  • 1970-01-01
  • 2014-03-17
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 2014-07-04
相关资源
最近更新 更多