gpt4 book ai didi

json - 从 documentDirectory 在本地编码/解码 JSON

转载 作者:行者123 更新时间:2023-11-28 14:52:53 24 4
gpt4 key购买 nike

我是 SWIFT 的新手,我正在尝试使用 JSON 文件 (financetoday.json) 中的数据来填充表格,供用户更新并将数据存储在设备上。该表具有折叠单元格(使用 XIB),每个单元格都有一个嵌入式 UISlider 来更新值。在我最初的工作中,我让表从包中成功加载 JSON 文件,填充表,然后 slider 更改每个值。现在是困难的部分。为了保存/更改数据,我需要将 JSON 文件移动到 documentDirectory 中,然后对该文件中的数据进行任何更改。一旦用户第一次启动应用程序,我不再需要使用包中的 JSON 文件,只需使用 documentDirectory 中的版本。我一直无法获取表来读取 documentDirectory 中的 JSON 文件。任何帮助,将不胜感激。这是我在 AppDelegate 中添加了一个方法,用于在文档目录中移动 JSON 文件

//将 json 文件从 bundle 移动到 documents 文件夹

var finalDatabaseURL:String = String()

函数 copyDatabaseIfNeeded() {

    let fileManager = FileManager.default

let documentsUrl = fileManager.urls(for: .documentDirectory,
in: .userDomainMask)

guard documentsUrl.count != 0 else {
return // Could not find documents URL
}

let finalDatabaseURL = documentsUrl.first!.appendingPathComponent("financetoday.json")

if !( (try? finalDatabaseURL.checkResourceIsReachable()) ?? false) {
print("DB does not exist in documents folder")

let documentsURL = Bundle.main.resourceURL?.appendingPathComponent("financetoday.json")

do {
try fileManager.copyItem(atPath: (documentsURL?.path)!, toPath: finalDatabaseURL.path)
} catch let error as NSError {
print("Couldn't copy file to final location! Error:\(error.description)")
}

} else {
print("Database file found at path: \(finalDatabaseURL.path)")
}

}

然后我添加到applicationDidBecomeActive

    self.copyDatabaseIfNeeded()

在我的数据模型中,这看起来像是从包中加载 JSON 数据,但我需要更改方法 dataFromFile 中的代码以使用 documentDirectory 中的 JSON 文件...而不是包。我所有更改结果的尝试都出现在一张空白表格中。所以现在我指向包中的 JSON。任何帮助将不胜感激。

import Foundation

public func dataFromFile(_ filename: String) -> Data? {
@objc class TestClass: NSObject { }

let bundle = Bundle(for: TestClass.self)

if let path = bundle.path(forResource: filename, ofType: "json") {
return (try? Data(contentsOf: URL(fileURLWithPath: path)))

}
return nil
}

class Plan {
var yeardata: Int?
var incomedata = [Income]()
var expensedata = [Expense]()
var assetdata = [Asset]()
var liabilitydata = [Liability]()
var profiledata = [Profile]()
var assumptiondata = [Assumption]()

init?(data: Data) {
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any], let myplan = json["data"] as? [String: Any] {

if let incomedata = myplan["incomedata"] as? [[String: Any]] {
self.incomedata = incomedata.map { Income(json: $0) }
}
if let expensedata = myplan["expensedata"] as? [[String: Any]] {
self.expensedata = expensedata.map { Expense(json: $0) }
}
if let assetdata = myplan["assetdata"] as? [[String: Any]] {
self.assetdata = assetdata.map { Asset(json: $0) }
}
if let liabilitydata = myplan["liabilitydata"] as? [[String: Any]] {
self.liabilitydata = liabilitydata.map { Liability(json: $0) }
}
if let profiledata = myplan["profiledata"] as? [[String: Any]] {
self.profiledata = profiledata.map { Profile(json: $0) }
}
if let assumptiondata = myplan["assumptiondata"] as? [[String: Any]] {
self.assumptiondata = assumptiondata.map { Assumption(json: $0) }
}
}
} catch {
print("Error deserializing JSON: \(error)")
return nil
}
}
}

class Income {
var key: String?
var value: Any?
init(json: [String: Any]) {
self.key = json["key"] as? String
self.value = json["value"] as Any
}
}
class Expense {
var key: String?
var value: Any?
init(json: [String: Any]) {
self.key = json["key"] as? String
self.value = json["value"] as Any
}
}
class Asset {
var key: String?
var value: Any?
init(json: [String: Any]) {
self.key = json["key"] as? String
self.value = json["value"] as Any
}
}
class Liability {
var key: String?
var value: Any?
init(json: [String: Any]) {
self.key = json["key"] as? String
self.value = json["value"] as Any
}
}
class Profile {
var key: String?
var value: Any?
init(json: [String: Any]) {
self.key = json["key"] as? String
self.value = json["value"] as Any
}
}
class Assumption {
var key: String?
var value: Any?
init(json: [String: Any]) {
self.key = json["key"] as? String
self.value = json["value"] as Any
}
}

最佳答案

这将读入 json。字典转换我不太熟悉,因为我已经开始使用 Codable我强烈推荐的协议(protocol)。

if let path = Bundle.main.path(forResource: "FileName", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
let jsonString = String(data: value, encoding: .utf8)
print("json as string: \(jsonString)")
let json = try JSONSerialization.data(withJSONObject: data, options: []) as? [String: Any]
print("json as dictionary: \(json)")
} catch let error {
print("parse error: \(error.localizedDescription)")
}
}

如何解码可编码数据:

    let decoder = JSONDecoder()
do {
let decodableJSON = try decoder.decode(ObjectConformingToCodable.self, from: data)
print(decodableJSON)
} catch let error {
print(error.localizedDescription)
}

关于json - 从 documentDirectory 在本地编码/解码 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49658663/

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