首页 > 解决方案 > 快速访问 json 的内部信息

问题描述

我检索了我的数据,但我需要的数据在第一个值“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()

标签: jsonswift

解决方案


正如评论中提到的,不要使用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) }

推荐阅读