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?
isValidJSONObject:
Returns a Boolean value that indicates whether a given object can be converted to JSON data.
Code Example
let jsonString = "{}"
let jsonData = jsonString.data(using: String.Encoding.utf8)
if JSONSerialization.isValidJSONObject(jsonData) {
print("Valid Json")
} else {
print("InValid Json")
}
API REFERENCE:
I have tested the following:
let jsonString = ""
let jsonString = "<html></html>"
let jsonString = "{}"
with code:
let jsonData: NSData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
var error: NSError? = nil
let validJson = (NSJSONSerialization.JSONObjectWithData(jsonData, options:nil, error: &error) != nil)
println("Valid JSON: \(validJson)")
First two strings print false
, the third prints true
as expected.
I think you are probably loading a different file than you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With