gpt4 book ai didi

json - 如何将 Swift 4 编码的 JSON 写入文件?

转载 作者:行者123 更新时间:2023-12-03 09:20:01 25 4
gpt4 key购买 nike

如何将通过 Swift 4 Codable 协议(protocol)编码的 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")

Data is not a valid format for JSON serialization:
{"numOfTeeth":48,"hobbies":["Dancing","Swiming","Eating people"],"name":"Nancy","carnivorous":true}
Data is not a valid format for JSON serialization: Optional(99 bytes)



如何让它通过 JSON 验证,然后将其写入文件?

最佳答案

JSON序列化 .您的 JSONSerialization.isValidJSONObject用法是错误的。作为文档 states :

A Foundation object that may be converted to JSON must have the following properties:
• The top level object is an NSArray or NSDictionary.
• All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
• All dictionary keys are instances of NSString.



因此, DataString类型根本无效;)

写入编码数据 .实际编写生成的 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)")
}
}

只要JSON数据由标准 JSONEncoder生成真的不需要额外的验证;)

关于json - 如何将 Swift 4 编码的 JSON 写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46763521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com