解析json并将Double转换为String(无法将类型' NSTaggedPointerString'(0x1098a1b90)的值转换为' NSNumber')

时间:2017-10-23 23:16:08

标签: json swift

我有一个像这样的Swift结构。

func parseData() {

    fetchedProduct = []
    let url = "http://www.koulourades.gr/api/products/get/?category=proionta"

    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "GET"

    let configuration = URLSessionConfiguration.default
    let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

    let task =  session.dataTask(with: request) { (data, response, error) in
        if  (error != nil) {
            print("Error")
        }
        else{
            do {
                let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray

                for eachFetchedProduct in fetchedData {
                    let eachProduct = eachFetchedProduct as! [String : Any]
                    let title = eachProduct ["ProductTitle"] as! String
                    let price = eachProduct ["ProductPrice"] as! Double

                    self.fetchedProduct.append(Product(title: title, price: price))
                }

                print(self.fetchedProduct)
                print(self.fetchedProduct.count)
            } catch {
              print("Error 2")
            }
        }
    }
    task.resume()     
}

class Product {

    var title: String
    var price: Double

    init(title: String, price: Double) {
        self.title = title
        self.price = price
    }
}

从API中,我得到以下JSON响应。(它是希腊语,还有更多属性,我只写了其中一些)

[  
   {

   "ProductTitle":"\u03a0\u03c1\u03b1\u03bb\u03af\u03bd\u03b1 OREO",

   "ProductSummary":"\u03bc\u03c0\u03b9\u03c3\u03ba\u03bf\u03c4\u03bf",

   "ProductPrice":"1.50",

   "ProductPriceGross":"1.86",

   "ProductPriceWithDiscount":"0.00", 

   "ProductImage":"koulouri_tyri_gemisto_philadelphia_galopoula_ntomata[1].jpg",

   },
...
]

但我只想采用 ProductPrice ProductTitle

Swift告诉我这个:无法转换类型的值' NSTaggedPointerString' (0x1098a1b90)到' NSNumber' (0x108eaa320)

而且,当我尝试仅使用StringThis的ProductTitle告诉我: 致命错误:在解包可选值时意外发现nil

我做错了什么?

1 个答案:

答案 0 :(得分:0)

JSON中的ProductPrice值是一个字符串,而不是一个double,这就是异常告诉你的内容;你不能强制将一个字符串向下转换为双精度。

您需要通过Double初始化程序

进行转换

根据您发布的信息,访问ProductTitle时不应出现异常,但最好避免强行解包/向下转发。仔细检查您的密钥名称中的输入错误。

一种“更安全”的方法(也避免了NSArray这是Swift的最佳实践):

if let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as? [[String:Any]] {

    for eachProduct in fetchedData {

       if let title = eachProduct ["ProductTitle"] as? String,
          let price = eachProduct ["ProductPrice"] as? String,
          let doublePrice = Double(price) {
              self.fetchedProduct.append(Product(title: title, price: doublePrice))

       }
    }
}