【发布时间】:2019-03-14 02:08:21
【问题描述】:
我需要同步两个 json 文件,以便在应用更新后将新内容从 File A(位于 app bundle 中)添加到 File B。
两个 json 文件都是字典数组。我需要从 File A 中迭代字典,并根据“id”值,如果 File B 中不存在字典,我需要附加那些缺失的字典并将文件B保存回文件系统。
我在下面有一个解决方案可以做到这一点,并且似乎有效。但是实在是太丑了!当然,我在大约 15 分钟内完成了这个工作,但我确信必须有更好的方法来处理这个问题。另外,我不想通过将这些字典转换为结构或模型进行比较来进一步混淆水域,只是为了将它们转换回字典-> json。
这里的任何建议都会很棒!我更喜欢干净的代码,但这是一团糟。
typealias JSON = [[String: Any]]
static private func uglySync() {
let fileName: String = "someFileName"
guard let sourceUrl = Bundle.main.url(forResource: fileName, withExtension: "json") else { return }
guard let destinationDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let destinationUrl = destinationDirectory.appendingPathComponent("Data/" + fileName + ".json")
do {
let sourceData = try Data(contentsOf: sourceUrl)
do {
if let sourceArray = try JSONSerialization.jsonObject(with: sourceData, options: .mutableContainers) as? JSON {
do {
let destinationData = try Data(contentsOf: destinationUrl)
do {
if let destinationArray = try JSONSerialization.jsonObject(with: destinationData, options: .mutableContainers) as? JSON {
var mutableArray = destinationArray
sourceArray.forEach({ (item) in
if let itemId = item["id"] as? String {
let foundItem = destinationArray.filter { $0["id"] as! String == itemId }.first
if foundItem == nil {
mutableArray.append(item)
}
}
})
do {
let jsonData = try JSONSerialization.data(withJSONObject: mutableArray, options: .prettyPrinted)
try jsonData.write(to: destinationUrl)
} catch let error as NSError {
print("Couldn't write to file: \(error.localizedDescription)")
}
} else {
print("Cound not process json")
}
} catch {
print(error.localizedDescription)
}
} catch {
print(error.localizedDescription)
}
} else {
print("Cound not process json")
}
} catch {
print(error.localizedDescription)
}
} catch {
print(error.localizedDescription)
}
// oh wow the try catches :/
}
【问题讨论】:
标签: arrays json swift dictionary