【问题标题】:Access the inner info of a json in swift快速访问 json 的内部信息
【发布时间】:2019-02-09 02:40:32
【问题描述】:

我检索了我的数据,但我需要的数据在第一个值“0”中,那么我如何访问“价格”或“产品名称”之类的内容

    ["0": {
        price = "4.77";
        productname = "KISSES Giant Milk Chocolate Candy, 7 oz";
    }]



URLSession.shared.dataTask(with: url!) { (data, response, err) in
        guard let data = data else {return}

        do {
            let json = try JSONSerialization.jsonObject(with: data) as! [String:Any]
            print(json)


        } catch let jsonErr {

        }

    }.resume()

【问题讨论】:

  • 实际上是stackoverflow.com/questions/54504391/… 和许多其他人的副本。停止使用 JSONSerialization。使用 Decodable 并深入了解并获取所需的信息。
  • @matt 我试过了,但由于结构不会取 0,它会给我一个错误

标签: json swift


【解决方案1】:

如 cmets 中所述,不要使用 JSONSerialization,使用 Decodable

使用 CodingKeys 将"0"翻译成合法的结构成员名称非常容易

struct Root: Decodable {
    let zero: Product

    private enum CodingKeys : String, CodingKey { case zero = "0" }
}

struct Product: Decodable {
    let price, productname : String
}

...

let jsonString = """
{"0":{"price":"4.77","productname":"KISSES Giant Milk Chocolate Candy, 7 oz"}}
"""

let data = Data(jsonString.utf8)
do {
    let result = try JSONDecoder().decode(Root.self, from: data)
    print(result.zero.productname)
} catch { print(error) }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-28
    • 2016-01-01
    • 1970-01-01
    • 2017-03-20
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    相关资源
    最近更新 更多