Search code examples
jsonswiftxcodensjsonserialization

JSON Serialization error. Swift conversion error from api response to json


Data from Server:

{"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}}}

its a valid json I checked on validator.

but its getting invalid json in swift conversion: below is the code:

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

Solution

  • Try this method to get Dictionary from json object.

        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 [:]
            }
        }