简体   繁体   中英

Swift4 / JSON / Decode

I'm new to Swift 4 and I looked for hours of hours to find a solution for my issue.

import Foundation 

public struct Coin: Codable {
  let name:   String //= "Default"
  let symbol: String
}

open class CoinCapIOAPI {

func fetchMap() {

    let urlString = "http://socket.coincap.io/map"
    guard let url = URL(string: urlString) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, error) in
        // Maybe later...
        guard let data = data else { return }

        do {

            let coins = try JSONDecoder().decode([Coin].self, from: data)
            print(coins)


        } catch let jsonErr {
            print("Error: ", jsonErr)
        }

        }.resume()
   }
}

The JSON looks like:

[
{ aliases: [ ],
name: "300 Token",
symbol: "300",
},
{
aliases: [ ],
name: "SixEleven",
symbol: "611",
},
]

I need just name and symbol . But without the default of name in the struct I get following error:

Error: keyNotFound(CoinBartender.Coin.(CodingKeys in _7C60C6A5E9E301137DE95AF645AB94EB).name, Swift.DecodingError.Context(codingPath: [Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: "Index 91", intValue: Optional(91))], debugDescription: "No value associated with key name (\\"name\\").", underlyingError: nil))

If I add the default value for "name" I get this result:

[CoinBartender.Coin(name: "Default", symbol: "300"), CoinBartender.Coin(name: "Default", symbol: "611"),

Why does symbol work but name doesn't?

Please read the error message carefully. It's exactly describing the issue:

Error: keyNotFound (CoinBartender.Coin.(CodingKeys in _7C60C6A5E9E301137DE95AF645AB94EB).name, Swift.DecodingError.Context(codingPath: [Foundation.(_JSONKey in _12768CA107A31EF2DCE034FD75B541C9)(stringValue: " Index 91 ", intValue: Optional(91))], debugDescription: " No value associated with key name (\\"name\\") .", underlyingError: nil))

It says that the 92nd entry (index is zero-based) does not have a key name

{"aliases":[],"symbol":"QTM"} 

One solution is to declare name as optional

let name: String?

Your Coin struct should be like this:

public struct Coin: Codable {
    let name:   String? //= "Default"
    let symbol: String
}

Because some indexes does not contain name .

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