简体   繁体   English

Swift4:从文件解码json时出错

[英]Swift4: Error while decoding json from file

This is my first post, so I hope everything is as structured as it should be. 这是我的第一篇文章,所以我希望一切都按原样安排。 I hope anybody can help me to solve my issue. 我希望任何人都可以帮助我解决我的问题。

I have the following issue while decoding JSON in Swift from a downloaded file: 从下载的文件在Swift中解码JSON时遇到以下问题:

The vocabulary.json file contains the following: vocabulary.json文件包含以下内容:

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

JSON in file 文件中的JSON

My swift 4 - code: 我的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)
        }
    }
}

If I decode the Json from the following multi string: 如果我从以下多个字符串解码Json:

    public let vokabeln: String = """
[
{
    "english": "one",
    "deutsch": "eins",
    "theme": "numbers"
},
{
    "english": "two",
    "deutsch": "zwei",
    "theme": "numbers"
}
]
"""

it works, but if I try to decode it from the file I receive the following error message: 它可以工作,但是如果我尝试从文件中解码它,则会收到以下错误消息:

failed to convert data dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}))) 无法转换数据dataCorrupted(Swift.DecodingError.Context(codingPath:[],debugDescription:“给定的数据不是有效的JSON。”,底层错误:可选(错误域= NSCocoaErrorDomain代码= 3840,JSON文本不是以数组或对象和允许未设置片段的选项。“ UserInfo = {NSDebugDescription = JSON文本不是以数组或对象开头,并且不允许设置片段的选项开头。}))

Thank you in advance. 先感谢您。

Kind regards, 亲切的问候,

Kai

Change this 改变这个

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

to this 对此

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

It will give an array of Vocabulary just like [Vocabulary] . 它会给阵列Vocabulary就像[Vocabulary]

I hope this will help you. 我希望这能帮到您。

I was getting a very similar error: 我收到一个非常类似的错误:

caught: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Badly formed object around character 64." UserInfo={NSDebugDescription=Badly formed object around character 64.}))) 捕获:dataCorrupted(Swift.DecodingError.Context(codingPath:[],debugDescription:“给定的数据不是有效的JSON。”,underlyingError:可选(错误域= NSCocoaErrorDomain代码= 3840“字符64附近格式错误的对象。” UserInfo = {NSDebugDescription =字符64附近格式错误的对象。})))

But for a completely different reason: 但是出于完全不同的原因:

My local json was created like this: 我的本地json是这样创建的:

"""
{
    "name": "Durian",
    "rate": 600,
    "city": "Cali"
    "description": "A fruit with a distinctive scent."
}
"""

The error message is quite obvious. 错误消息非常明显。 I had forgot to place , after "Cali". 我已经忘了把, “卡利”之后。

If I understand this correctly, to count 64 characters you have to start counting from the beginning of the line where "name" is. 如果我理解正确,那么要计数64个字符,就必须从“名称”所在行的开头开始计数。 Meaning there are 4 empty characters before in each line. 表示每行前面有4个空字符。 Hence the number ~64. 因此,数字约为64。 You don't need to count the spaces at the line of { :) 您无需在{ :)行中计算空格

Placing the comma resolved the issue. 放置逗号即可解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM