【问题标题】:How to parse JSON values using Swift 4?如何使用 Swift 4 解析 JSON 值?
【发布时间】:2019-01-02 14:42:28
【问题描述】:

GET **Place** 值和来自 JSON 响应下方的值,我需要存储到数组中以供 tableview UISearchbar 搜索。

[{
    "id": 1,
    "class": "A",
    "Place": {
        "city": "sando",
        "state": "CA"
    }
 }, {
    "id": 1,
    "class": "B",
    "Place": {
        "city": "jambs",
        "state": "KA"
    }
 }]

我尝试使用以下代码,请帮助我获取特定值。

let url = URL(string: "http://*****.com/file.php")!
let request = URLRequest(url: url)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data else {
        print("request failed \(error)")
            return
    }

    do {
        if let json = try JSONSerialization.jsonObject(with: data) as? [String: String], let result = json["result"] {
            // Parse JSON
        }
    } catch let parseError {
        print("parsing error: \(parseError)")
        let responseString = String(data: data, encoding: .utf8)
            print("raw response: \(responseString)")
        }
    }
    task.resume()
}

【问题讨论】:

  • 有无数示例和教程展示了如何在 Swift 中解析 JSON 数据。请做一些基础研究并尝试一些事情。然后用您的相关代码更新您的问题,并清楚地解释您尝试过的内容以及遇到的问题。作为提示,请搜索 JSONDecoder。
  • 好的,现在您已经发布了代码,但您还没有发布任何信息,您需要对代码有什么帮助。请edit您的问题,并提供有关您在代码中遇到的确切问题的相关详细信息。
  • 我需要获取 id、class、city 和 state 值并存储到表数组中。 @rmaddy

标签: ios json swift search tableview


【解决方案1】:

您的代码无法运行。根据给定的 JSON,根对象是一个数组 [[String: Any]],根本没有键 result

let json = """
[{"id":1,"class":"A","Place":{"city":"sando","state":"CA"}},{"id":1,"class":"B","Place":{"city":"jambs","state":"KA"}}]
"""

let data = Data(json.utf8)

do {
    if let json = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] {
        for item in json {
            if let place = item["Place"] as? [String:String] {
                print(place["city"]!, place["state"]!)
            }
        }
    }
} catch let parseError {
    print("parsing error: \(parseError)")
    let responseString = String(data: data, encoding: .utf8)
    print("raw response: \(responseString!)")
}

使用Decodable 协议将JSON解析成结构体更方便

struct Response : Decodable {

    private enum  CodingKeys: String, CodingKey { case id, `class`, place = "Place" }

    let id : Int
    let `class` : String
    let place : Place
}

struct Place : Decodable {
    let city, state : String
}

...

do {
    let result = try JSONDecoder().decode([Response].self, from: data)
    for item in result {
        print(item.place.city, item.place.state)
    }
} catch { print(error) }

【讨论】:

  • 它不工作@vadian。它没有打印任何内容。
  • 如果收到的 JSON 的格式与问题中的 JSON 完全匹配,则它必须有效。
  • 我在 Playground 中使用这个 JSON 测试了代码。我确实工作。该错误必须与加载数据的代码有关。你有错误吗?
  • 我没有收到错误。如果您找到结果,请编辑您的代码。谢谢@vadian
  • 我添加了能够在 Playground 中独立测试代码的行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-05
  • 1970-01-01
  • 2018-10-21
相关资源
最近更新 更多