【发布时间】:2018-01-02 12:06:23
【问题描述】:
这是我的第一篇文章,所以我希望一切都像它应该的那样结构化。 我希望任何人都可以帮助我解决我的问题。
我在 Swift 中从下载的文件中解码 JSON 时遇到以下问题:
词汇表.json 文件包含以下内容:
[
{
"english": "one",
"deutsch": "eins",
"theme": "numbers"
},
{
"english": "two",
"deutsch": "zwei",
"theme": "numbers"
}
]
我的 swift 4 - 代码:
public struct Vocabulary: Codable{
let english: String
let deutsch: String
let theme: String
}
func decodeData(){
DataManager.getJSONFromURL("vokabeln") { (data, error) in
guard let data = data else {
return
}
let decoder = JSONDecoder()
do {
let vocabulary = try decoder.decode(Vocabulary.self, from: data)
print(vocabulary)
} catch let e {
print("failed to convert data \(e)")
}
}
}
public final class DataManager {
public static func getJSONFromURL(_ resource:String, completion:@escaping (_ data:Data?, _ error:Error?) -> Void) {
DispatchQueue.global(qos: .background).async {
let url = URL(string: "https://onedrive.live.com/xxxxx/vokabeln.json")
let data = try! Data(contentsOf: url!, options: .uncached)
completion(data, nil)
}
}
}
如果我从以下多字符串中解码 Json:
public let vokabeln: String = """
[
{
"english": "one",
"deutsch": "eins",
"theme": "numbers"
},
{
"english": "two",
"deutsch": "zwei",
"theme": "numbers"
}
]
"""
它可以工作,但如果我尝试从文件中解码它,我会收到以下错误消息:
数据转换失败 dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text没有开始带有数组或对象以及允许未设置片段的选项。" UserInfo={NSDebugDescription=JSON 文本未以数组或对象开头,并且允许未设置片段的选项。})))
提前谢谢你。
亲切的问候,
启
【问题讨论】:
-
您的 JSON 是一个字典数组,因此根据您的
Vocabulary类,它应该是一个词汇对象数组。 -
将 URL 粘贴到浏览器中并检查 JSON 是否有效。错误消息说不是。并且从不使用
Data(contentsOf从远程 URL 加载数据。 -
好的,谢谢您的提示。我该如何加载它?