json - 在 Swift 上转义 json 字符串

标签 json swift

在使用 SWIFT 的 iPhone 应用程序中,我不得不处理第三方 API,该 API 发送转义字符串而不是 JSON 对象作为响应。

响应看起来像这样:

"[
{
\"ID\":3880,
\"Name\":\"Exploration And Production Inc.\",
\"ContractNumber\":\"123-123\",
\"Location\":\"Booker #1\",
\"Volume\":1225.75,
\"OtherFees\":10.0
}
]"

到目前为止,我一直通过操作字符串来删除不需要的字符来处理这个问题,直到我得到一个类似 JSON 的字符串,然后像往常一样解析它。

Angular 有一个方便的函数来处理这个问题:

angular.fromJson(response.data);

Java有自己的处理方式。 Swift 中有等效函数吗?

最佳答案

如果您将其解析为字典,那么最简单的解决方案是将 String 转换为 Data 并使用 JSONSerialization:

if let data = string.data(using: .utf8) {
    do {
        let responseArray = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]]
        print(responseArray)
    }
    catch {
        print(error)
    }
}

但是当然最好将它作为一个 Codable 模型来处理,在这种情况下它又很简单:

try JSONDecoder().decode([Item].self, from: data)

前提是你有一个有效的 Decodable 模型,如下所示:

struct Item: Decodable {
    let id: Int
    let name: String
    //add the other keys you want to use (note its type sensitive)

    enum CodingKeys: String, CodingKey {
         case id = "ID"
         case name = "Name"
    }
}

最后,避免使用字符串化的 json,因为它很容易出错。
格式错误的字符串或结构中的小/大偏差很容易被忽视。
让后端团队知道他们应该在其 API 中遵循消费者可以依赖的协议(protocol)。
通过设置json格式,它本质上就像一个契约(Contract),清晰地展示了它的内容和目的。
发送一个字符串化的 json 只是懒惰,并且对它的设计者的影响很差,恕我直言。

关于json - 在 Swift 上转义 json 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56296866/

相关文章:

java - 用Jackson写yaml?

c# - 需要解析通过 Post 请求传入的 JSON

json - 为什么在Json Grails中将Joda LocalTime渲染为String?

node.js - JSONAPI实现

ios - 使用 Swift 和 Storyboard 在两个 UIViewController 之间传递数据

ios - Swift 3 和 backendless - 我如何上传图片?

javascript - 如何获取复杂对象的 JSON 字符串值?

swift - 在 'foo' 调用之前的方法调用 'super.init' 中使用了“self”

ios - 滚动时表格 View 数据重复

swift - 创建 Swift 闭包以创建 UIView