【问题标题】:What's the easiest way to parse a JSON in Swift 4?在 Swift 4 中解析 JSON 的最简单方法是什么?
【发布时间】:2018-09-02 16:39:00
【问题描述】:

我编写了以下函数来使用 Alamofire 在我的 macOS 应用程序中执行 GET 请求:

func getContent(room: String) -> String {
let scriptUrl = "https://klipped.in/api/\(room)"
Alamofire.request(scriptUrl).responseJSON { response in        
    if let json = response.result.value {
        print("\(json)") // serialized json response
    }
}
return "This should return the value of \"content\" in the json response"
}

我现在想以最有效的方式解析 json。我在谷歌上搜索了执行此操作的方法,但我发现的每个解决方案似乎都过于复杂或由于类型问题而无法运行。

在 Swift 中是否有一种简单的方法可以访问 JSON 中的值,而无需为每个响应创建 Struct?我正在考虑以下方面的事情:

get-json-value(json, "content")

这将返回 json 中“content”的字符串值,如果不存在则返回 null。

【问题讨论】:

  • 它的重复问题。尝试使用搜索。这是答案。 stackoverflow.com/a/50383222/8417137
  • 如果您能够读取 JSON,最有效的方法是 Codable。如果没有,没有简单的方法。
  • 最简单的方法是做一些研究。
  • 我已经阅读了答案,发现解析 JSON 必须写这么多 LOC 很奇怪。我只是想问是否有任何库可以使这个过程更快。

标签: json swift


【解决方案1】:

在 Swift 4 中使用 Alamofire 解析 JSON 的最简单方法是使用

getRoomData = JSON as NSDictionary
str = getRoomData["content"] as String

请参阅以下示例: AlamoFire GET api request not working as expected

更好的方法是使用Swifty JSON 库:

let json = JSON(responseData.result.value!)
let roomContent = json["content"].string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    • 2011-02-08
    • 1970-01-01
    • 2013-07-06
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多