简体   繁体   中英

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:

The vocabulary.json file contains the following:

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

JSON in file

My swift 4 - code:

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:

    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.})))

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] .

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.})))

But for a completely different reason:

My local json was created like this:

"""
{
    "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. Meaning there are 4 empty characters before in each line. Hence the number ~64. You don't need to count the spaces at the line of { :)

Placing the comma resolved the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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