gpt4 book ai didi

ios - Swift4:从文件解码json时出错

转载 作者:行者123 更新时间:2023-12-01 19:46:53 26 4
gpt4 key购买 nike

这是我的第一篇文章,所以我希望所有内容都应该结构合理。
我希望任何人都可以帮助我解决我的问题。

从下载的文件在Swift中解码JSON时出现以下问题:

vocabulary.json文件包含以下内容:

[
{
"english": "one",
"deutsch": "eins",
"theme": "numbers"
},
{
"english": "two",
"deutsch": "zwei",
"theme": "numbers"
}
]

JSON in file

我的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:“给定的数据不是有效的JSON。”,底层错误:可选(错误域= NSCocoaErrorDomain代码= 3840,JSON文本不是以数组或对象和允许未设置片段的选项。“UserInfo = {NSDebugDescription = JSON文本不是以数组或对象开头,并且不允许设置片段的选项开头。}))

先感谢您。

亲切的问候,

最佳答案

改变这个
let vocabulary = try decoder.decode(Vocabulary.self, from: data)
对此

let vocabulary = try decoder.decode([Vocabulary].self, from: data)

就像 Vocabulary一样,它将给出一个 [Vocabulary]数组。

我希望这能帮到您。

关于ios - Swift4:从文件解码json时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48060711/

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