lundi 31 août 2015

Swift - check if JSON is valid

let data = NSData(contentsOfFile: "myfile")
let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)
let jsonData: NSData! = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
var validJson = false

if (NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) != nil) {
    validJson = true
}

I want the code above to only set validJson true when the contents of jsonData is actually valid JSON. At the moment if I pump anything into the "myfile" file which can be seen in the code, validJson is always true.

How can I fix this so validJson is only true when it's actually valid JSON?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire