如何将此字典转换为数组或访问值? {x = "1.1"; y = "2.3";}

How to cast this dictionary to an array or to get access to the values? {x = "1.1"; y = "2.3";}

我正在使用 api 来获取一些数据。 json 在其字段之一中具有此数据结构。

这是访问我的 json 的代码:

let myUrl = NSURL(string:"http://openmensa.org/api/v2/canteens/\(choosenID)/days/" + currentDate + "/meals")!


    URLSession.shared.dataTask(with: myUrl as URL) { (data, response, error) in
        if error != nil {
            print(error!)
        } else {
            do {
                if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [[String:Any]] {
                    print(json) 
                    for entry in json {
                        if let userId = entry["id"], let name = entry["name"], let category = entry["category"], let price = entry["prices"], let notes = entry["notes"] {
                            var meal = MealObject(id:userId as! Int, name:name as! String as! String, category:category as! String, price:0.0, notes: notes as! [String]);

                            print(price)
                                                           // DO MY OTHER STUFF...
                        }
                    }
                } else {
                    print("JSON is not an array of dictionaries")
                }
            } catch let error as NSError {
                print(error)
            }
        }
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
        }.resume()

打印(json):

[["name": Macaroni & Cheese, "id": 2915045, "category": Tagesgericht 3, "prices": {
    employees = "2.6";
    others = "3.1";
    pupils = "<null>";
    students = "1.9";
}, "notes": <__NSArrayI 0x600000298380>(
Schwefeldioxid und Sulfite,
Senf,
Milch und Laktose,
Weizen,
Glutenhaltiges Getreide,
Alkohol,
mit Farbstoff
)
],

打印(价格):

{
    employees = "1.9";
    others = "2.4";
    pupils = "<null>";
    students = 1;
},
{
    employees = "2.6";
    others = "3.1";
    pupils = "<null>";
    students = "1.9";
}

我可以毫无问题地访问 id、类别或注释!唯一的问题是价格。

我怎样才能访问这个数据结构?我想将双精度值保存到数组中。

您尝试过使用 "SwiftyJSON" Cocoapods 吗?如果没有,我建议安装 "SwiftyJSON" 。然后如下图所示简单

let json = data

let employees = json["employees"]
let others = json["others"]
let pupils = json["pupils"]
let students = json["students"]

如果你有兴趣,你可以通过这个link https://cocoapods.org/?q=swiftyjs
You may need to go through this 如果你不知道 cocoapods 的使用或安装

Paulw11 在评论中给出了答案:

我不知道的数据结构是字典里面的json。

我更改了我的代码:

if let userId = entry["id"], let price = entry["prices"]

对此:

if let userId = entry["id"], let price = entry["prices"] as? [String:Any]]

现在我可以这样使用它了:

var employer = price["employees"]

感谢 Paulw11;)