解析 JSON 没有对象的文件 Swift
Parse JSON file with no objects Swift
我正在尝试用 Swift 解析以下 JSON 文件。我不知道如何解析没有对象的文件,所以任何帮助都会很棒。下面是示例 JSON
[
"sleeping bag",
"Arabian camel, dromedary, Camelus dromedarius",
"water"
]
我设置的解码文件的代码如下
struct ItemsStruct: Codable {
let item: String
}
public extension Decodable{
static func fromFile<T : Decodable>(_ filename : String, class : T.Type)->T?{
let fileparts = filename.split(separator: ".")
guard fileparts.count == 2 else{
return nil
}
guard let path = Bundle.main.url(forResource: String(fileparts[0]), withExtension: String(fileparts[1])),
let data = try? Data.init(contentsOf: path),
let _struct = try? JSONDecoder().decode(T.self, from: data) else{
return nil
}
return _struct
}
}
guard let items = ItemsStruct.fromFile("objects.json", class: [ItemsStruct].self) else {return}
for item in items{
print(item)
}
我知道我不应该 "let item: String" 但我不确定要在结构中放入什么,因为没有对象。
我需要不同的 JSON 数据吗?
是String
的数组
guard let items = [String].fromFile("objects.json", class: [String].self) else {return}
for item in items{
print(item)
}
顺便说一句,语法很奇怪。并且您应该使方法 throw
移交所有可能的错误,而不是返回一个可选的并忽略所有错误。
我正在尝试用 Swift 解析以下 JSON 文件。我不知道如何解析没有对象的文件,所以任何帮助都会很棒。下面是示例 JSON
[
"sleeping bag",
"Arabian camel, dromedary, Camelus dromedarius",
"water"
]
我设置的解码文件的代码如下
struct ItemsStruct: Codable {
let item: String
}
public extension Decodable{
static func fromFile<T : Decodable>(_ filename : String, class : T.Type)->T?{
let fileparts = filename.split(separator: ".")
guard fileparts.count == 2 else{
return nil
}
guard let path = Bundle.main.url(forResource: String(fileparts[0]), withExtension: String(fileparts[1])),
let data = try? Data.init(contentsOf: path),
let _struct = try? JSONDecoder().decode(T.self, from: data) else{
return nil
}
return _struct
}
}
guard let items = ItemsStruct.fromFile("objects.json", class: [ItemsStruct].self) else {return}
for item in items{
print(item)
}
我知道我不应该 "let item: String" 但我不确定要在结构中放入什么,因为没有对象。
我需要不同的 JSON 数据吗?
是String
guard let items = [String].fromFile("objects.json", class: [String].self) else {return}
for item in items{
print(item)
}
顺便说一句,语法很奇怪。并且您应该使方法 throw
移交所有可能的错误,而不是返回一个可选的并忽略所有错误。