JSON encode/decoding 和 swift 4
JSON encode/decoding with swift 4
Swift 4.0 iOS 11.2.x
我在这里创建了一个名为 products 的 Codable 结构,并使用此方法将其保存到文件中。
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' 而终止应用程序,原因:'* +[NSJSON序列化dataWithJSONObject:options:error:]: JSON 中的无效顶级类型写入'
我做错了什么;我怎样才能将 json 写入文件以便我可以读回它!!具有讽刺意味的是,几天前我用 plist 制作了这段代码,我讨厌 json.
为什么要将结构编码为 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
不带问号 do 捕获错误。
Swift 4.0 iOS 11.2.x
我在这里创建了一个名为 products 的 Codable 结构,并使用此方法将其保存到文件中。
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' 而终止应用程序,原因:'* +[NSJSON序列化dataWithJSONObject:options:error:]: JSON 中的无效顶级类型写入'
我做错了什么;我怎样才能将 json 写入文件以便我可以读回它!!具有讽刺意味的是,几天前我用 plist 制作了这段代码,我讨厌 json.
为什么要将结构编码为 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
不带问号 do 捕获错误。