如何使用SWIFT解析json中的多维数组

时间:2015-07-02 04:22:34

标签: ios json swift multidimensional-array

这是我的示例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数组但是输出只是出现在“Order”中的列表我只需要使用“OrderID”。任何人都可以帮我解决问题

1 个答案:

答案 0 :(得分:-1)

尝试使用SwiftyJSON库

https://github.com/SwiftyJSON/SwiftyJSON

它简化了一切。