Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create decodable of nested array in swift?

Background: I’m using swift Alamofire@5.6.2 and I need to parse json data

AF.request("https://xxx.json").validate().responseDecodable(of: Decodable)

The data looks like:

[
   [
       "a",
       123,
       1.0,
   ],
   [
       "b",
       456,
       2.0,
   ],
]

My code (this is the wrong way):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

struct Item: Codable {
   var name: String
}

...responseDecodable(of: [Item].self)

Should I use enum instead? I read some similar answers but they all have keys at some point, my data is pure array without keys.

>Solution :

Assuming the types are always the same in the same order this is a simple example how to decode the inner array, the struct member names are arbitrary

struct Item: Decodable {
    let name: String
    let someInt: Int
    let someDouble: Double
    
    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        name = try container.decode(String.self)
        someInt = try container.decode(Int.self)
        someDouble = try container.decode(Double.self)
    }
}

and decode [Item].self

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading