gpt4 book ai didi

json - 无法使用SwiftyJSON访问JSON数据

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

我正在尝试访问一些 JSON 数据,但无法使用 swiftyJSON 访问该数据。我收到了 JSON 响应,因此我使用 alamofire 获取它。这是 JSON:

{"groupID":"6","groupName":"Test","teacher":"teacher1 
","teacherID":"13","Locations":
[{"locationID":"5","locationName":"field"},
{"locationID":"6","locationName":"34th"}],"Error":""}

我正在使用打印语句来调试错误。这是我尝试使用的代码:

                    let json = JSON(response.result.value ?? "error")
//let jsonError = json["Error"]
print("=================<JSON RESPONSE>=================");
print(json)
print("=================</JSON RESPONSE/>=================");

self.groupID = json["groupID"].stringValue
self.groupName = json["groupName"].stringValue
self.teacherID = json["teacherID"].stringValue
let locjson = json["Locations"]


print("Entering LocJSON Loop")
print("=================<LOCJSON >=================");
print("GNAME:" + self.groupID)
print("TID: " + json["teacherID"].stringValue)
print("Locjson.stringalue: " + locjson.stringValue)


//print("LocationJSON" + json["Locations"]);
print("=================</LOCJSON/>=================");

for (key, object) in locjson {
print("In LocJSON Loop")
let locationIDVar: Int? = Int(key)
self.locations[locationIDVar!].locationID = locationIDVar!
self.locations[locationIDVar!].locationName = object.stringValue
print(self.locations[locationIDVar!].locationName)
print(object);
}

这是与打印语句相对应的控制台输出。

=================<JSON RESPONSE>=================
{"groupID":"6","groupName":"Test","teacher":"Teacher1"
,"teacherID":"13","Locations":
[{"locationID":"5","locationName":"field"},
{"locationID":"6","locationName":"34th"}],"Error":""}
=================</JSON RESPONSE/>=================
Entering LocJSON Loop
=================<LOCJSON >=================
GNAME:
TID:
Locjson.stringalue:
=================</LOCJSON/>=================

此外,如何到达“位置”内的多个位置?

最佳答案

Locations的值是一个包含字典的数组。

    let locjson = json["Locations"].arrayValue
for location in locjson {
let locID = location["locationID"].stringValue
let locName = location["locationName"].stringValue
print(locID, locName)
}

在 Swift 4 中,我更喜欢 Decodable 而不是 SwiftyJSON,因为你可以直接解码为结构。

关于json - 无法使用SwiftyJSON访问JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51196277/

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