JSON 序列化错误。 Swift 从 api 响应到 json 的转换错误
JSON Serialization error. Swift conversion error from api response to json
来自服务器的数据:
{"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 我检查了验证器。
但它在 swift 转换中变得无效 json:下面是代码:
if (JSONSerialization.isValidJSONObject(dataR!)){
let jsonResponse = try JSONSerialization.data(withJSONObject: dataR!, options: .prettyPrinted)
if let response = jsonResponse as? [String: Any]{
尝试使用此方法从 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 [:]
}
}
来自服务器的数据:
{"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 我检查了验证器。
但它在 swift 转换中变得无效 json:下面是代码:
if (JSONSerialization.isValidJSONObject(dataR!)){
let jsonResponse = try JSONSerialization.data(withJSONObject: dataR!, options: .prettyPrinted)
if let response = jsonResponse as? [String: Any]{
尝试使用此方法从 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 [:]
}
}