将从JSONResponse解析的值放到全局数组swift 3中

时间:2017-09-01 12:56:03

标签: ios parsing swift3 alamofire

如何使用从JSONResponse全局解析的值。因此,能够从JSONResponse中提取数组,但之后尝试将该数组放入全局数组中,而不是如何声明全局数组。不知何故设法做到了但现在无法从该数组中提取索引值。请指导。

现在尝试使用代码:

if (JSONResponse["status"].intValue == 1)
        {

            if let fetchedImages = JSONResponse["data"].arrayObject {
                self.arrResponseReceived = fetchedImages
            }
            print("self.arrResponseReceived", self.arrResponseReceived)
        }
        else
        {
            CommonMethodsClass.showAlertMessage(vc: self, titleStr: "Error!", messageStr: strMsg)
        }

之前尝试过的代码:

arrResponseReceived = JSONResponse["data"].arrayValue

为数组声明的全局变量是:

var arrResponseReceived : [Any] = []

要解析的数据是:

  {
    data =     (
                {
            AverageRating = 4;
            Image = "<null>";
            IsActive = 1;
            Latitude = "28.567806";
            Longitude = "77.3236273";
            SalonAddress = " Sec-58, India";
            SalonEmail = "vy.chan@th-rce.com";
            SalonID = 1;
            SalonImage = "";
            SalonMobile = 9999888877;
            SalonName = Affinity;
            SalonPhone = 9999888877;
            TimeIntervalminutes = 20;
        },
                {
            AverageRating = 5;
            Image = "<null>";
            IsActive = 1;
            Latitude = "";
            Longitude = "";
            SalonAddress = "Mall, India";
            SalonEmail = "rad@th-rce.com";
            SalonID = 3;
            SalonImage = "";
            SalonMobile = 9999888877;
            SalonName = Looks;
            SalonPhone = 9999888877;
            TimeIntervalminutes = 30;
        }
    );
    message = "";
    status = 1;
}

1 个答案:

答案 0 :(得分:0)

你应该明确JSONResponse [“data”]里面的类.arrayValue,或Xcode如何知道它。 如果你想得到一个由Dictionary组成的数据数组,这就是我欺骗它的方法。

func getDatas(from json: Any?) -> [Dictionary] {
    guard let json = json as? NSDictionary, let entries = json.value(forKeyPath: "data") as? [NSDictionary] else {
        return []
    }

    return entries.flatMap { entry in
        guard let dictionary = entry as? NSDictionary else {
            return nil
        }
        return dictionary
    }
}

你这样称呼它

self.arrResponseReceived = getDatas(from: json)

NSDictionary的方法值(forKeyPath :)接近魔法。调用json.value(forKeyPath:“data”)会返回一个字典数组。每个字典都是json中的“入口”对象。接下来,我映射每个返回字典的条目。

如果这不仅仅是一个快速解决方案,那么我会考虑将SwiftyJSON添加到您的项目中。

func getDatas(from json: Any?) -> [Dicitonary] {
    return JSON(json)["data"].arrayValue.flatMap { entry in
        guard let dictionary = entry as? NSDictionary else {
            return nil
        }
        return dictionary
    }
}