Swift ObjectMapper:如何使用反斜杠解析JSON

时间:2018-12-17 22:25:20

标签: json swift alamofire

我已经在stackoverflow上尝试了几乎所有可能的解决方案,到目前为止还算不上成功,

这是我的json响应:

[
    "{\"id\":5,\"request_id\":\"rqst5c17fc752d44f1.15452158\",\"business_name\":\"611 Solutions\",\"business_email\":\"611thesolutions@gmail.com\",\"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\"}"
]

请注意,json的键和值中存在反斜杠,并且我的解析失败,这就是我解析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)

    }
}

我也尝试过使用.responseString来获取纯字符串并执行let json = response.result.value?.replacingOccurrences(of: "\\", with: "")并像let jobs = Mapper<JobResponseDataObject>().map(JSONString: json!)这样映射它,到目前为止也没有运气。请帮助

谢谢

1 个答案:

答案 0 :(得分:2)

您可以尝试

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
}
相关问题