json - 无法使用 SwiftyJSON 访问 JSON 数据
问题描述
我正在尝试访问一些 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/>=================
另外,我如何到达“位置”内的多个位置?
解决方案
key 的值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,因为您可以直接解码为结构。
推荐阅读
- apache-spark - 带有 ScalaPB 的 SparkSQL:从 DataFrame 转换为原型数据集时跳过原型字段时出错
- java - 将 GET 请求的响应保存为类对象
- javascript - MVC / javascript竞争条件?
- android - 尽管进行了长时间的搜索并使用了许多解决方案,但我无法实现此代码
- oauth - Amazon Cognito 是否支持“地址”范围?好像不见了
- azure-devops - 如何运行 VSTest.Console 动态数量的项目?
- python-3.x - Python x Zebra - 如何打印标签
- r - 在 R 中查找每个分组的新观察值
- android - 如何从火力基地取消身份验证禁用帐户?
- google-cloud-platform - Google 的 API Gateway 和 Cloud Endpoints 之间的区别