【问题标题】:Swift ObjectMapper: How to parse JSON with backslashSwift ObjectMapper:如何使用反斜杠解析 JSON
【发布时间】:2018-12-17 22:25:19
【问题描述】:

我已经尝试了几乎所有关于 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&lt;JobResponseDataObject&gt;().map(JSONString: json!) 那样映射它,到目前为止也没有运气。请帮忙

谢谢

【问题讨论】:

  • 响应是一个数组,其中包含一个项目,该项目是另一个 JSON 字符串。
  • 我们可以帮助您解析这个,但是正确的解决方案是修复任何提供这个的服务,这样它就不会在数组中包含另一个 JSON 字符串。你有能力改变网络服务吗?
  • 你好,很遗憾没有,这个回复来自我的队友,来自 php 脚本,有他可以使用的 3rd 方 api 吗?
  • @Rob 你能指导我如何使用对象映射器解析这个吗?谢谢
  • 如果它是一种演示/小型应用程序,那么您可以继续弄乱响应以制作有效的 json,但如果它不仅仅是一个小项目,那么它应该立即在后端修复.

标签: json swift alamofire


【解决方案1】:

你可以试试

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
}

【讨论】:

    【解决方案2】:

    您不需要删除反斜杠 - 它只是再序列化一次,这意味着它需要反序列化回来。 看:Why json response includes backward slashes in web api response

    只需从字符串项中创建一个数据对象:

    let data = stringItem.data(using: .utf8)
    

    然后使用 JSONDecoder 正常解码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多