Bad*_*Cat 4 serialization json swift swift4 codable
如何将通过Swift 4 Codable协议编码的JSON对象写入文件?斯威夫特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")
}
Run Code Online (Sandbox Code Playgroud)
这两种格式都无效JSONSerialization.isValidJSONObject():
JSON.writeToStream(data: jsonString, path: "\(NSHomeDirectory())/Documents")
JSON.writeToStream(data: jsonString.data(using: .utf8), path: "\(NSHomeDirectory())/Documents")
Run Code Online (Sandbox Code Playgroud)
数据不是JSON序列化的有效格式:
{"numOfTeeth":48,"爱好":["跳舞","游泳","吃人"],"名称":"南希","食肉":真实}
数据不是JSON序列化的有效格式:可选(99字节)
如何将其传递给JSON验证然后将其写入文件?
Pau*_*tos 10
JSONSerialization.你的JSONSerialization.isValidJSONObject用法是错误的.正如文件明确指出:
可以转换为JSON的Foundation对象必须具有以下属性:
•顶级对象是NSArray或NSDictionary.
•所有对象的实例NSString,NSNumber,NSArray,NSDictionary,或NSNull.
•所有字典键都是实例NSString.
因此,Data或String类型根本无效;)
编写编码数据.要实际编写生成的内容Data,请使用相应的Data.write(to: URL)方法.例如:
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)")
}
}
Run Code Online (Sandbox Code Playgroud)
只要标准生成JSON数据,就JSONEncoder不需要进行额外的验证;)
| 归档时间: |
|
| 查看次数: |
6271 次 |
| 最近记录: |