首页 > 解决方案 > 无法使用 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/>=================

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

标签: jsonswiftxcodealamofireswifty-json

解决方案


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 中,我更喜欢DecodableSwiftyJSON,因为您可以直接解码为结构。


推荐阅读