验证大型JSON密钥

时间:2017-06-23 13:06:51

标签: json swift validation parsing

我收到大量的JSON数据,我需要知道任何密钥是否为零。

我通常做这样的事情(使用SwiftyJSON):

guard let
 name = json["username"].string,
 firstEpisodeAiredText = json["firstEpisodeAired"].string,
 firstEpisodeAired = formatter.dateFromString(firstEpisodeAiredText),
 seasons = json["seasons"].int,
 genres = (json["genres"].array?.flatMap { $0.string })
else { return nil }

问题是我可以从同一个请求中获得数百个密钥: 有没有更简单的方法来测试我的密钥与零值?

1 个答案:

答案 0 :(得分:0)

首先SwiftyJSON中的键不是可选的,因此它们不能 nil

其次要验证JSON的所有数据,您应该迭代JSON的每个元素。

示例:

class func validation(with json:JSON) -> Bool {

    guard let jsonDictionary = json.dictionary else {
        return false
    }

    let keys = jsonDictionary.keys //All keys of the Dictionary 

    for key in keys {

        guard let data = jsonDictionary[key] else { //If data is nil return false
            return false
        }

        print("JSON data: \(data)")
    }

    return true
}