Swift / Alamofire:遍历JSON值以检查bool值吗?

时间:2018-12-24 16:13:27

标签: json swift alamofire

这是JSON:

sudo cat /proc/$(pidof mongod)/status

我试图遍历此JSON数据以查看isCurrentSeason是否为true。如果是真的,我需要存储它的“ id”。

这是我当前的实现方式:

 {
  "data": [
    {
      "type": "season",
      "id": "season.1",
      "attributes": {
        "isCurrentSeason": true,
        "isOffseason": false
      }
    },
    {
      "type": "season",
      "id": "season2",
      "attributes": {
        "isCurrentSeason": false,
        "isOffseason": false
      }
    }
}

在案例.Success行上,我不断收到错误Alamofire.request(request).responseJSON { response in switch response.result { case .Success(let _data): print(_data) if let DataObject = _data["data"] as? NSDictionary { if let Attributes = DataObject["attributes"] as? [NSDictionary] { for attribute in Attributes { if Attributes["isCurrentSeason"] = true { currentSeasonID = Attributes["isCurrentSeason"] } } } } default: break; } } 。因此,我什至无法测试它是否提取正确的数据。不确定是否有更好的方法来遍历和记录数据。

3 个答案:

答案 0 :(得分:0)

首先,您不应该使用NSDictionary代替Swift的Dictionary。其次,您不使用与响应中返回的类型相同的类型转换data。当您将其强制转换为array时,它应该是dictionary中的dictionary,它将始终失败。我不确定您使用的是哪个版本的Alamofire,但是在当前版本中,枚举Result<Any>成功的案例是camelCase,即.success(let data)。如果出现错误,请使用您已经拥有的错误,即.Success(let data)。下面是固定版本,

Alamofire.request(request).responseJSON { response in
    typealias JSON = [String: Any]
    switch response.result {
    case .success(let data):
        guard let json = data as? JSON, let objects = json["data"] as? [JSON] else { return }
        for object in objects {
            if let attributes = object["attributes"] as? JSON,
                let currentSession = attributes["isCurrentSeason"] as? Bool,
                currentSession == true {
                print(currentSession)
                print(object["id"] as! String)
                break
            }
        }
    default:
        print("Error occured")
    }
}

答案 1 :(得分:0)

错误清楚地表明,_data(带有下划线的变量非常 c-ish )是Any,因此您必须对此进行条件下调类型。如果期望的类型是字典,请考虑使用更具体的Result<[String:Any]>

请阅读JSON。很简单集合类型只有两种,数组([])和字典({}),因此键data的值是一个数组,键attributes的值是一个字典

并且请遵循命名约定,即变量以小写字母开头,在Swift中不要使用NSArrayNSDictionary

switch response.result {

        case .Success(let response):

            if let response = response as? [String:Any],
               let data = response["data"] as? [[String:Any]] {
               for item in data {
                   if let attributes = item["attributes"] as? [String:Bool],
                      let isCurrentSeason = attributes["isCurrentSeason"], isCurrentSeason == true {
                         currentSeasonID = isCurrentSeason
                         break // add this to exit the loop immediately if the item was found
                   }
               }
            }
        default:
            break
        }

但是我猜currentSeasonID应该是id的值,而不是布尔值isCurrentSeason

        case .Success(let response):

            if let response = response as? [String:Any],
               let data = response["data"] as? [[String:Any]] {
               for item in data {
                   if let identifier = item["id"] as? String,
                      let attributes = item["attributes"] as? [String:Bool],
                      let isCurrentSeason = attributes["isCurrentSeason"], isCurrentSeason == true {
                         currentSeasonID = identifier
                         break // add this to exit the loop immediately if the item was found
                   }
               }
            }
        default:
            break
        }

答案 2 :(得分:-1)

您可以尝试

if let content =  _data as? [String:Any] {
    if let dataObject = content["data"] as? [[String:Any]] {
            dataObject.forEach {
             if let attributes = $0["attributes"] as? [String:Bool] { 
                if attributes["isCurrentSeason"] == true { 
                    print("This is true")
                }
            }
        }
    }
}

您的data是字典数组,而attributes是字典