How to write a Swift 4 encoded JSON to a file?
JSONSerialization. Your JSONSerialization.isValidJSONObject
usage is wrong. As the documentation states:
A Foundation object that may be converted to JSON must have the following properties:
• The top level object is anNSArray
orNSDictionary
.
• All objects are instances ofNSString
,NSNumber
,NSArray
,NSDictionary
, orNSNull
.
• All dictionary keys are instances ofNSString
.
As such, Data
or String
types aren’t valid at all ;)
Writing the encoded data. To actually write the generated Data
, use the corresponding Data.write(to: URL)
method instead. For instance:
if let encodedData = try? JSONEncoder().encode(obj) {
let path = "/path/to/obj.json"
let pathAsURL = URL(fileURLWithPath: path)
do {
try encodedData.write(to: pathAsURL)
}
catch {
print("Failed to write JSON data: \(error.localizedDescription)")
}
}
As long as the JSON data is generated by the standard JSONEncoder
no additional validation is really made necessary ;)