如何将通过 Swift 4 Codable 协议编码的 JSON 对象写入文件?在 Swift 4 之前我使用过JSONSerialization.writeJSONObject
,但JSONSerialization.isValidJSONObject
现在返回false
创建的数据(或字符串)。一个例子:
import Foundation
class Shark : Codable
{
var name:String = ""
var carnivorous:Bool = true
var numOfTeeth:Int = 0
var hobbies:[String] = []
}
class JSON
{
class func encode<T:Encodable>(_ obj:T) -> String?
{
if let encodedData = try? JSONEncoder().encode(obj)
{
return String(data: encodedData, encoding: .utf8)
}
return nil
}
class func writeToStream(data:Any, path:String) -> Bool
{
var success = false
if JSONSerialization.isValidJSONObject(data)
{
if let stream = OutputStream(toFileAtPath: "\(path)", append: false)
{
stream.open()
var error:NSError?
JSONSerialization.writeJSONObject(data, to: stream, options: [], error: &error)
stream.close()
if let error = error
{
print("Failed to write JSON data: \(error.localizedDescription)")
success = false
}
}
else
{
print("Could not open JSON file stream at \(path).")
success = false
}
}
else
{
print("Data is not a valid format for JSON serialization: \(data)")
success = false
}
return success
}
}
let shark = Shark()
shark.name = "Nancy"
shark.carnivorous = true
shark.numOfTeeth = 48
shark.hobbies = ["Dancing", "Swiming", "Eating people"]
if let jsonString = JSON.encode(shark)
{
let success = JSON.writeToStream(data: jsonString.data(using: .utf8), path: "\(NSHomeDirectory())/Documents")
}
这两种格式都无效JSONSerialization.isValidJSONObject()
:
JSON.writeToStream(data: jsonString, path: "\(NSHomeDirectory())/Documents")
JSON.writeToStream(data: jsonString.data(using: .utf8), path: "\(NSHomeDirectory())/Documents")
数据不是 JSON 序列化的有效格式:
{"numOfTeeth":48,"hobbies":["Dancing","Swiming","Eating people"],"name":"Nancy","carnivorous":true}
数据不是 JSON 序列化的有效格式:可选(99 字节)
如何让它通过 JSON 验证,然后将其写入文件?