Parsing JSON into Swift Objects

January 11, 2019 · By Preston Rohner · Programming · Swift

One of the kind of neat, newer features in Swift is that you can create classes that are Codable. In the app, I get some JSON from the server. Here’s the abridged JSON:

{
    data =     {
        "can_access_orders" = 1;
        "can_access_reports" = 1;
    };
    message = "";
    status = 200;
}

You can create Swift structs that mirror the JSON and then decode (with data type validations/translations) easily. Here’s the corresponding Swift struct

struct UserPermissionsRequest : Codable {
    let permissions: UserPermissions   // This references the structure below, contained within the structure
    let message: String
    let status: Int
    
    enum CodingKeys : String, CodingKey {
        case permissions = "data"
        case message
        case status
    }
    
    struct UserPermissions : Codable {
        let canAccessOrders: Bool
        let canAccessReports: Bool
        
        enum CodingKeys : String, CodingKey {
            case canAccessOrders = "can_access_orders"   // Mapping a JSON key into a Swift struct member
            case canAccessReports = "can_access_reports"
        }
    }
}

Then the code to convert the JSON into structs is simply: .

let userPermissions = try decoder.decode(UserPermissionsRequest.self, from: data)

And then later

if userPermissions.permissions.canAccessOrders {
    // Do stuff here 
}