Swift Codable: Array of Array having Dictionaries

swift decodable array of objects
swift codable nested dictionary
swift codable nested array
swift codable dictionary<string: any
swift dictionary to object
swift decode array of objects
swift decode json array
swift decodable dictionary

I have a JSON object, I cannot figure out how to access the exclude_list in given JSON.

{"variants":
    {"variant_groups":
            [
                    {
                        "group_id":"1",
                        "name":"Crust",
                        "variations":[
                            {"name":"Thin","price":0,"default":1,"id":"1","inStock":1},
                            {"name":"Thick","price":0,"default":0,"id":"2","inStock":1,"isVeg":1},
                            {"name":"Cheese burst","price":100,"default":0,"id":"3","inStock":1,"isVeg":1}]},

                    {
                        "group_id":"3",
                        "name":"Sauce",
                        "variations":[
                            {"name":"Manchurian","price":20,"default":0,"id":"20","inStock":1,"isVeg":0},
                            {"name":"Tomato","price":20,"default":0,"id":"21","inStock":1,"isVeg":1},
                            {"name":"Mustard","price":20,"default":0,"id":"22","inStock":1,"isVeg":0}]

                    }],
            "exclude_list":[
                [
                    {"group_id":"1","variation_id":"3"},
                    {"group_id":"2","variation_id":"10"}
                ],
                [
                    {"group_id":"2","variation_id":"10"},
                    {"group_id":"3","variation_id":"22"}
                ]
            ]
    }
}

I can access properties like: variants, variant_groups using below Struct:

public struct VariantResponse: Codable {

    public let variants: Variants
}
public struct Variants: Codable {

    public let variantGroups:[VariantGroup]
    public let excludeList:[ExcludeItems]
}
public struct VariantGroup: Codable {
    public let groupId: String
    public let name: String
    public let variations: [Variant]
}
public struct Variant: Codable {
    public let name: String
    public let price: Int
    public let defaultValue: Int
    public let id: String
    public let inStock: Int
    public var isVeg: Int?

    private enum CodingKeys : String, CodingKey {
        case name, price, defaultValue = "default", id, inStock, isVeg
    }    
}
public struct ExcludeItems: Codable {
    public let excludes:[Exclude]
}
public struct Exclude: Codable {
    public let groupId: String
    public let variationId: String
}

You can try

struct VariantResponse: Codable {
    let variants: Variants
}

struct Variants: Codable {
    let variantGroups: [VariantGroup]
    let excludeList: [[ExcludeItems]]

}

struct ExcludeItems: Codable {
    let groupId, variationId: String

}

do {

    let dec = JSONDecoder()
    dec.keyDecodingStrategy = .convertFromSnakeCase
    let res = try dec.decode(VariantResponse.self, from: data)

}
catch {

    print(error)
}

ExcludeItems contains groupId, variationId but you add unknown key excludes

Why Dictionary sometimes encodes itself as an array – Ole Begemann, In Swift's Codable system, only dictionaries with String or Int keys have noticed that some dictionaries encode themselves as arrays in Swift's� You may have noticed that some dictionaries encode themselves as arrays in Swift’s Codable system — or more precisely, as unkeyed containers, which is Codable lingo for an array-like data structure. This is quite surprising; a keyed container sounds like a much better match for a dictionary. Here’s an example.

you have some problems in decodable structs , try to use this code :

    public struct VariantResponse: Codable {
    public let variants: Variants
}

public struct Variants: Codable {
    public let variant_groups:[VariantGroup]
    public let exclude_list:[[Exclude]]
}

public struct VariantGroup: Codable {
    public let group_id: String
    public let name: String
    public let variations: [Variant]
}

public struct Variant: Codable {
    public let name: String
    public let price: Int
    public let defaultValue: Int
    public let id: String
    public let inStock: Int
    public var isVeg: Int?

    private enum CodingKeys : String, CodingKey {
        case name, price, defaultValue = "default", id, inStock, isVeg
    }
}

public struct Exclude: Codable {
    public let group_id: String
    public let variation_id: String
}

Wishes best luck.

Swift Codable: Array of Dictionaries - arrays - php, I have a JSON object from Yelp and I cannot figure out how to access the title in categories using Swift Codable. This is the JSON (with some elements removed� With the array of loans (i.e. jsonLoans) returned, we loop through the array. Each of the array items (i.e. jsonLoan) is converted into a dictionary. In the loop, we extract the loan data from each of the dictionaries and save them in a Loan object. Again, you can find the keys (highlighted in yellow) by studying the JSON result.

The issue may be with the coding keys in your model. Please refer the following Model for fetching your JSON structure.

struct VariantsResponse: Codable {
    let variants: Variants?
}

typealias VariantGroups = [VariantGroup]
typealias ExcludeLists = [[ExcludeList]]
typealias Variations = [Variation]

struct Variants: Codable {
    let variantGroups: VariantGroups?
    let excludeList: ExcludeLists?

    enum CodingKeys: String, CodingKey {
        case variantGroups = "variant_groups"
        case excludeList = "exclude_list"
    }
}

struct ExcludeList: Codable {
    let groupId, variationId: String?

    enum CodingKeys: String, CodingKey {
        case groupId = "group_id"
        case variationId = "variation_id"
    }
}

struct VariantGroup: Codable {
    let groupId, name: String?
    let variations: Variations?

    enum CodingKeys: String, CodingKey {
        case groupId = "group_id"
        case name, variations
    }
}

struct Variation: Codable {
    let name: String?
    let price, variationDefault: Int?
    let id: String?
    let inStock, isVeg: Int?

    enum CodingKeys: String, CodingKey {
        case name, price
        case variationDefault = "default"
        case id, inStock, isVeg
    }
}

In the above model, I am creating typealias for the following arrays, for making the model more human readable and understandable.

typealias VariantGroups = [VariantGroup]
typealias ExcludeLists = [[ExcludeList]]
typealias Variations = [Variation]

here we are defining codingKeys case for variables which cannot convert directly to an attribute of the model.

Hope this will helps you to create the model.

You can simply decode the model with the responseData using the following code

let decoder = JSONDecoder()
let res = try decoder.decode(VariantsResponse.self, from: responseData)

Here if we specify the decoder.keyDecodingStrategy = .convertFromSnakeCase we didn't need to specify the codingKeys like case groupId = "group_id". The system will automatically inspect the _ character and convert the JSON key string to camelCaseKeys.

Decode Array<Any> and Dictionary<String, Any> Swift � GitHub, @loudmouth, did you have a license in mind for this gist? Looks just like the kind of thing I've been looking for, to work with my Codable stuff for JSON parsing. The only requirement Codable has is that all the properties inside the struct also conform to Codable – in our case that’s a string and an integer, so we’re all set. Start by adding this type: struct Person: Codable { var name: String var age: Int } Now we can go ahead and decide the JSON data into an array of that Person struct.

Codable protocol in swift 4., Apple introduced a Codable protocol in Swift 4 - A new way to Having seen examples of decoding dictionaries and arrays, now it the time to� With Swift 4 and later you can now use the Codable protocol. Your Swift struct or class merely has to adopt that protocol, and you get JSON encoding and decoding for free . The Codable protocol is a composition of two protocols, Decodable and Encodable .

Serializing a dictionary with any codable values - Using Swift, Codable can't encode and decode a dictionary that contains codable heterogeneous elements. So, compared to NSCoding, we have a mechanism that makes serializing archivedData(withRootObject: array as NSArray,� Apple has introduced a new way to decode and encode the JSON data using Codable since Swift 4. means parse the JSON data into a dictionary that contains the array of students on a key.

JSONDecoder().decode([String: Any]…, At that time, arrays and dictionaries declared conformance with Codable, but In the current version of Swift, it's possible to have conditional conformance, since� Swift’s simple types like String and Int automatically conform to Codable, and arrays and dictionaries also conform to Codable if they contain Codable objects. That is, [String] conforms to Codable just fine, because String itself conforms to Codable.