Search code examples
jsonswiftalamofire

Swift ObjectMapper: How to parse JSON with backslash


I have tried pretty much all the potential solutions on stackoverflow and so far no luck,

This is my json response:

[
    "{\"id\":5,\"request_id\":\"rqst5c17fc752d44f1.15452158\",\"business_name\":\"611 Solutions\",\"business_email\":\"[email protected]\",\"title\":\"123ABC - TESTING\",\"details\":\"Package is fragile, please haul with care\",\"load_description\":\"Royal Timber\",\"amount_offered\":\"2500\",\"pickup_address\":\"123 Colliumeal Dr, Fort Wayne, Indiana\",\"dropoff_address\":\"647 Airportway, Chicago, Illinois\",\"timestamp\":\"2018-12-17 19:43:49\"}"
]

Notice there are backslashes within the key and values of the json and my parsing is failing, this is how I am parse the json:

Alamofire.request(JOB_REQUEST_BASE_URL, method: .post, parameters: parameter, encoding: URLEncoding(), headers: nil).responseArray { (response: DataResponse<[JobResponseDataObject]>) in

    log.debug("Fetching Job Requests...")

    switch response.result {

    case .success(let responseArray) :
        log.debug(response.debugDescription)
        log.debug("Sucessfully fetch job requests")
        log.debug("Job request counts: \(responseArray.count)")
        completionHandler(JobRequest.fetchJobRequest.Response(jobResponses: responseArray), nil)

    case .failure(let error) :

        log.debug("Fetching error: JobRequest")
        log.debug(error.localizedDescription)
        completionHandler(nil, .FailedToFetchEmptyJobRequests)

    }
}

I have also tried fetching the pure string using .responseString and doing let json = response.result.value?.replacingOccurrences(of: "\\", with: "") and mapping it like so let jobs = Mapper<JobResponseDataObject>().map(JSONString: json!) so far no luck too. Please help

Thanks


Solution

  • You can try

    if let str = responseArray.first as? String , let data = str.data(using:.utf8) {
    
       do {
            let decoder = JSONDecoder() 
            decoder.keyDecodingStrategy = .convertFromSnakeCase
            let res = try decoder.decode(Root.self,from:data)
        }
       catch {
        print(error)
       }
    }
    
    struct Root: Codable {
        let id: Int
        let requestId, businessName, businessEmail, title: String
        let details, loadDescription, amountOffered, pickupAddress: String
        let dropoffAddress, timestamp: String
    }