【问题标题】:JSON Serialization error. Swift conversion error from api response to jsonJSON 序列化错误。从 api 响应到 json 的 Swift 转换错误
【发布时间】:2019-11-29 07:48:40
【问题描述】:

来自服务器的数据:

{"status":{"id":5,"title_en":"Accepted By Restaurant","title_restaurant":"In progress","title_rider":"New","title_customer":"In progress","slug":"accepted_by_restaurant","active":1},"orderDetail":{"id":47,"user_customer_id":27,"user_restaurant_id":13,"user_rider_id":null,"coupon_data":null,"order_status_id":5,"cancelled_by":null,"order_description":"Dsadas","reason_for_cancellation":null,"order_type":"delivery","vat":0,"delivery_fee":0,"total":200,"rider_rating":null,"customer_rating":null,"restaurant_rating":null,"service_rating":null,"reviews":null,"created_at":"2019-11-29 12:38:11","order_status":{"id":5,"title_en":"Accepted By Restaurant","title_restaurant":"In progress","title_rider":"New","title_customer":"In progress","slug":"accepted_by_restaurant","active":1}}}

它是我在验证器上检查的有效 json。

但它在快速转换中得到无效的 json:下面是代码:

if (JSONSerialization.isValidJSONObject(dataR!)){
   let jsonResponse = try JSONSerialization.data(withJSONObject: dataR!, options: .prettyPrinted)
   if let response = jsonResponse as? [String: Any]{

【问题讨论】:

  • 如果您收到数据,您需要JSONSerialization.jsonObject(with:options:)

标签: json swift xcode nsjsonserialization


【解决方案1】:

试试这个方法从json对象中获取字典。

    func getDictionaryFromJsonString(dictString:String)-> [String: Any] {
        do {
            return try  JSONSerialization.jsonObject(with: 
            dictString.data(using: 
            String.Encoding.utf8, allowLossyConversion: true)!, options:  
             JSONSerialization.ReadingOptions.allowFragments) as! Dictionary
        } catch {
            return [:]
        }
    }

【讨论】:

  • 我会避免强制展开。它们返回可选值是有原因的。除非你对你的应用崩溃没有问题,否则不要这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多