gpt4 book ai didi

ios - JSON key :value pairs disappearing after original json call

转载 作者:行者123 更新时间:2023-11-30 11:27:30 24 4
gpt4 key购买 nike

我一直在尝试使用 Swift 从 JSON 读取数据,但在原始 json 调用后它一直不起作用。这是我的有效代码:

func loadUrl(url:String){
DispatchQueue.global().async {
do {
let appUrl = URL(string:url)!
let data = try Data(contentsOf:appUrl)
let json = try JSONSerialization.jsonObject(with: data) as! [String:Any]
DispatchQueue.main.async {
print(json)
}
} catch {
DispatchQueue.main.async {
print("Cannot connect to the server.")
}
}
}
}

它打印这个结果:

["results": <__NSSingleObjectArrayI 0x60000000ae80>(
{
"address_components" = (
{
"long_name" = Brooklyn;
"short_name" = Brooklyn;
types = (
political,
sublocality,
"sublocality_level_1"
);
},
{
"long_name" = "New York";
"short_name" = "New York";
types = (
locality,
political
);
},
{
"long_name" = "Kings County";
"short_name" = "Kings County";
types = (
"administrative_area_level_2",
political
);
},
{
"long_name" = "New York";
"short_name" = NY;
types = (
"administrative_area_level_1",
political
);
},
{
"long_name" = "United States";
"short_name" = US;
types = (
country,
political
);
}
);
"formatted_address" = "Brooklyn, NY, USA";
geometry = {
bounds = {
northeast = {
lat = "40.739446";
lng = "-73.83336509999999";
};
southwest = {
lat = "40.551042";
lng = "-74.05663";
};
};
location = {
lat = "40.6781784";
lng = "-73.94415789999999";
};
"location_type" = APPROXIMATE;
viewport = {
northeast = {
lat = "40.739446";
lng = "-73.83336509999999";
};
southwest = {
lat = "40.551042";
lng = "-74.05663";
};
};
};
"place_id" = ChIJCSF8lBZEwokRhngABHRcdoI;
types = (
political,
sublocality,
"sublocality_level_1"
);
}
)
, "status": OK]

但是,我想做的是一直到 formatted_address 键。然而,当我尝试这段代码时,程序崩溃了:

func loadUrl(url:String){
DispatchQueue.global().async {
do {
let appUrl = URL(string:url)!
let data = try Data(contentsOf:appUrl)
let json = try JSONSerialization.jsonObject(with: data) as! [String:Any]
let results = json["results"] as! [String:Any]
DispatchQueue.main.async {
print(results)
}
} catch {
DispatchQueue.main.async {
print("Cannot connect to the server.")
}
}
}
}

有人知道如何解决这个问题吗?我唯一注意到的是结果的值(value)是:

<__NSSingleObjectArrayI 0x604000206d60>

我不知道这是什么。当我将相同的 json 放入在线查看器时,该值只是 0。这是为什么? “results”的值不应该是address_components、formatted_address、geometry、place_id和types吗?

最佳答案

你可以试试吗

if let results = json["results"] as? [[String:Any]] {

if let first = results[0] as? [String:Any] {
print(first["formatted_address"])
}
}

关于ios - JSON key :value pairs disappearing after original json call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50573738/

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