无法使用SwiftyJSON访问JSON数据

时间:2018-07-05 16:38:23

标签: json swift xcode alamofire swifty-json

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

contact = InputPhoneContact(client_id = 0, phone = phone, first_name="a", last_name="")
result = client(ImportContactsRequest([contact]))
usersDic = result.__dict__['users']
if(len(usersDic)>0):
    chatID = usersDic[0].__dict__["id"]

我正在使用打印语句来调试问题。这是我要使用的代码:

{"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);
                    }

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

1 个答案:

答案 0 :(得分:0)

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,因为您可以直接解码为结构。