解析服务器响应中的字符串数组的问题

时间:2018-04-11 13:03:15

标签: ios json swift

我有来自api响应的以下json字符串...

    ["products": <__NSArrayI 0x7fa103868000>(
    {
        barcode = HDz;
        "category_json" = "[{\"category_name\":\"Home\",\"category_id\":\"2\"}]";
        "created_at" = "2018-04-09 12:56:35";
        "discount_price" = "5000.00";
.....

我正在解析这个回复......

if httpResponse.statusCode == 200 {

                        print("SUCCESS!")

                        if let result = response.result.value as? [String:Any] {
                            print(result)

                            guard let products = result["products"] as? [[String:Any]] else {
                                return
                            }

                            for value in products {
                                if let barcode = value["barcode"] as? String {
                                    self.theBarcode = barcode
                                }

                                if let discountPrice = value["discount_price"] as? String {
                                    self.theDiscountRate = discountPrice
                                }
                                //Issue arises here
                                guard let category = value["category_json"] as? [[String: Any]] else {
                                    return
                                }

一切正常。但当我到达类别部分时,控件返回并发生退出。不知道为什么会这样......

1 个答案:

答案 0 :(得分:1)

"category_json":"[{\"category_name\":\"Home\",\"category_id\":\"2\"}]"

JSON中的JSON(字符串化)。

你的工具是什么:
Dictionary or Array对象&lt; =(通过)JSONSerialization)=&gt; Data对象
String对象&lt; =&gt; Data对象

因此您需要使用JSONSerialization()再次解析它。

let categoryStringified = "[{\"category_name\":\"Home\",\"category_id\":\"2\"}]"
//in your case let categoryStringified = value["category_json"] as String
let categoryStringifiedData = categoryStringified.data(using: .utf8)
let categories = try? JSONSerialization.jsonObject(with: categoryStringifiedData!, options: []) as! [[String: Any]]
print("categories: \(categories)")
for aCategory in categories {
   ...
}

旁注:为了逻辑起见,我强行打开包装,没有在catch上执行try?等。 您已经知道如何管理它们(您使用guard letif let等。)