7

如何将通过 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 验证,然后将其写入文件?

4

2 回答 2

16

JSON序列化。你的JSONSerialization.isValidJSONObject用法是错误的。正如文档所述

可以转换为 JSON 的 Foundation 对象必须具有以下属性:
• 顶级对象是NSArrayor NSDictionary
• 所有对象都是NSStringNSNumberNSArrayNSDictionary或的实例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)")
    }
}

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

于 2017-10-16T14:01:58.530 回答
0

要添加到@Paulo 答案,也可以使用与JSONEncoder使用类似的方式指定输出格式JSONSerialization。为此,您需要创建一个JSONEncoder实例并将其outputFormatting属性设置为您想要的值(它必须是 的实例JSONEncoder.OutputFormatting)。

例子:

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

if let encodedData = try? encoder.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)")
    }
}

现在encodedData将使用适当的缩进和换行符编写。

于 2020-12-31T10:45:37.117 回答