如何将通过 Swift 4 Codable 协议(protocol)编码的 JSON 对象写入文件?在 Swift 4 之前,我使用了 JSONSerialization.writeJSONObjectJSONSerialization.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 验证,然后将其写入文件?

最佳答案

JSONSerialization 。您的JSONSerialization.isValidJSONObject用法错误。作为文档states:



因此,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生成的,就没有必要进行其他验证了;)

10-08 08:49