【问题标题】:JSON encode/decoding with swift 4使用 swift 4 进行 JSON 编码/解码
【发布时间】:2018-08-14 19:51:06
【问题描述】:

Swift 4.0 iOS 11.2.x

我在这里创建了一个名为 products 的 Codable stuct,并使用此方法将其保存到文件中。

 func saveImage() {
    let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    let file2ShareURL = documentsDirectoryURL.appendingPathComponent("config.n2kHunt")

    var json: Any?
    let encodedData = try? JSONEncoder().encode(products)
    if let data = encodedData {
        json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
        if let json = json {
            do {
                try String(describing: json).write(to: file2ShareURL, atomically: true, encoding: .utf8)
            } catch {
                print("unable to write")
            }
        }
    }
}

它有效,假设我输入了两条记录,我将其存档。 [不是 json,而是随便什么]。

(
    {
    identity = "blah-1";
    major = 245;
    minor = 654;
    url = "https://web1";
    uuid = f54321;
},
    {
    identity = "blah-2";
    major = 543;
    minor = 654;
    url = "https://web2";
    uuid = f6789;
}

)

我将文件空投到第二台 iOS 设备,并尝试在 appDelegate 中使用此过程对其进行解码。

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

    do {
        let string2D = try? String(contentsOf: url)
        let jsonData = try? JSONSerialization.data(withJSONObject: string2D)
        do {
            products = try JSONDecoder().decode([BeaconDB].self, from: jsonData!)
        } catch let jsonErr {
            print("unable to read \(jsonErr)")
        }

    }  catch {
        print("application error")
    }
   }

我遇到了母亲崩溃,并带有此错误消息...

2018-03-06 21:20:29.248774+0100 blah[2014:740956] * 由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'* +[NSJSONSerialization dataWithJSONObject:options:错误:]:JSON 写入中的顶级类型无效'

我做错了什么;如何将 json 写入文件以便我可以读回它!具有讽刺意味的是,几天前我使这段代码与 plist 一起工作,我讨厌 json。

【问题讨论】:

    标签: ios json decode swift4 encode


    【解决方案1】:

    为什么要将结构编码为 JSON,然后将 JSON 反序列化为 Swift 数组并将集合类型字符串表示(!)保存到磁盘?反之则无法工作,这会导致错误。

    这更容易:

    func saveImage() {
        let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        let file2ShareURL = documentsDirectoryURL.appendingPathComponent("config.n2kHunt")
    
        do {
            let encodedData = try JSONEncoder().encode(products)
            try encodedData.write(to: file2ShareURL)
        } catch {
            print("unable to write", error)
        }
    }
    

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    
        do {
            let jsonData = try Data(contentsOf: url)
            products = try JSONDecoder().decode([BeaconDB].self, from: jsonData)
        } catch {
            print("unable to read", error)
        }
    }
    

    注意事项:

    • 从不catch 子句中打印无意义的文字字符串,至少打印实际的 error
    • 从不do - catch 块中写入 try?。写try 不带问号捕捉错误。

    【讨论】:

    • 感谢瓦迪安;我刚刚得到这个代码,只有我的不如你的 Try?还有这个那个!现在有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多