gpt4 book ai didi

swift - 如何从复杂的字典中获取值?

转载 作者:行者123 更新时间:2023-11-28 08:59:46 25 4
gpt4 key购买 nike

API 在下面返回此响应,但我不知道如何解析它。

响应 JSON

[
"results": [
[
"address": "mgG2W14th6TXYWXNDrZ24shsJ2wYhJm2b3",
"total": [
"balance": 0,
"received": 0,
"sent": 0
],
"confirmed": [
"balance": 0,
"received": 0,
"sent": 0
]
]
]
]

快速代码

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.chain!.getAddress(address!) { dictionary, error in
NSLog("%@", dictionary)
}

字典对象

(lldb) po dictionary
[results: (
{
address = mgG2W14th6TXYWXNDrZ24shsJ2wYhJm2b3;
confirmed = {
balance = 0;
received = 0;
sent = 0;
};
total = {
balance = 0;
received = 0;
sent = 0;
};
}
)]

我试了很多次了...你能分享一下如何解决吗..

(lldb) po dictionary["results"]![0]
{
address = mgG2W14th6TXYWXNDrZ24shsJ2wYhJm2b3;
confirmed = {
balance = 0;
received = 0;
sent = 0;
};
total = {
balance = 0;
received = 0;
sent = 0;
};
}

po dictionary["results"]![0]!["address"]
error: <EXPR>:1:28: error: cannot subscript a value of type 'AnyObject' with an index of type 'String'
dictionary["results"]![0]!["address"]

我在“let address = ...”行得到“Could not find member 'subscript'”。

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.chain!.getAddress(address!) { dictionary, error in
NSLog("%@", dictionary)

let address = dictionary["results"]![0]["address"]!
print("address: \(address)")
}

最佳答案

if let myDictionary = dictionary as? [String:AnyObject] {
if let results = myDictionary["results"] as? [AnyObject] {
if let firstItem = results[0] as? [String: AnyObject] {
if let address = firstItem["address"] as? String {
print(address)
}
if let total = firstItem["total"] as? [String:Int] {
if let balance = total["balance"] {
print(balance)
}
if let received = total["received"] {
print(received)
}
if let sent = total["sent"] {
print(sent)
}
}
if let confirmed = firstItem["confirmed"] as? [String:Int] {
if let balance = confirmed["balance"] {
print(balance)
}
if let received = confirmed["received"] {
print(received)
}
if let sent = confirmed["sent"] {
print(sent)
}
}
}
}
}

为了简化事情,如果返回的数据始终具有相同的格式,您可以创建一个类来管理此类解析。

关于swift - 如何从复杂的字典中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32186862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com