Anviking / Decodable

[Probably deprecated] Swift 2/3 JSON unmarshalling done (more) right
MIT License
1.04k stars 73 forks source link

How to decode without a specific key? #133

Closed Arcovv closed 7 years ago

Arcovv commented 7 years ago

This is my struct:

struct ReaderDirectoryWeight { let sourceName: String let weight: Int }

The "sourceName" is assigned by a dictionary key, and the "weight" is assigned by the key value.

There is the example:

"weights": { "Text/Cover.xhtml": 4, "Text/Introduction.xhtml": 209, "Text/AboutAuthor.xhtml": 423, "Text/Part1.xhtml": 428, "Text/Ch1-01.xhtml": 2234, "Text/Ch1-02.xhtml": 3947 }

It's my solution:

` typealias ReaderDirectoryWeightType = [String: Int]

static func decode(_ json: Any) throws -> [ReaderDirectoryWeight] {

guard let dictionary = json as? JSONDictionary, let weightDirectory = dictionary["weights"] as? ReaderDirectoryWeightType else {
    throw DecodingError.typeMismatch(
        expected: ReaderDirectoryWeightType.self,
        actual: type(of: json),
        DecodingError.Metadata(path: ["weights"], object: json, rootObject: nil))
}

return weightDirectory.flatMap(ReaderDirectoryWeight.init)

}`

Has a better solution? Thanks!

Anviking commented 7 years ago

Although dictionaries can't be Decodable, there are many different ways of decoding them. For instance, you should be able to do this:

let weightDirectory: [String: Int] = try json => "weights"
return weightDirectory.flatMap(ReaderDirectoryWeight.init)
Arcovv commented 7 years ago

Thank you!