How to Build a custom data model for search query and user detail using Unlash Api?

38 Views Asked by At

I am building an app that lets users search for photos. I am in the process of creating a data model using a codable. Below is the JSON data. The data model will contain id, created_at, username, name, portfolio_url, and images. How do I access the nested user and image information in the user dictionary and URL images.

 {
        "id": "LBI7cgq3pbM",
        "created_at": "2016-05-03T11:00:28-04:00",
        "updated_at": "2016-07-10T11:00:01-05:00",
        "width": 5245,
        "height": 3497,
        "color": "#60544D",
        "blur_hash": "LoC%a7IoIVxZ_NM|M{s:%hRjWAo0",
        "likes": 12,
        "liked_by_user": false,
        "description": "A man drinking a coffee.",
       
      "user": {
          "id": "pXhwzz1JtQU",
          "username": "poorkane",
          "name": "Gilbert Kane",
          "portfolio_url": "https://theylooklikeeggsorsomething.com/",
          "bio": "XO",
          "location": "Way out there",
          "total_likes": 5,
          "total_photos": 74,
          "total_collections": 52,
          "instagram_username": "instantgrammer",
          "twitter_username": "crew",
          "
          },
     "urls": {
            "raw": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f",
            "full": "https://hd.unsplash.com/photo-1416339306562-f3d12fefd36f",
            "regular": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&s=92f3e02f63678acc8416d044e189f515",
            "small": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&s=263af33585f9d32af39d165b000845eb",
            "thumb": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max&s=8aae34cf35df31a592f0bef16e6342ef"
          },
1

There are 1 best solutions below

0
udbhateja On

When using Codable you need to follow the hierarchy of the model.

Use three structs or classes as:

struct URLs: Codable {
    var raw: String
    var full: String
    var regular: String
    var small: String
    var thumb: String
}

struct User: Codable {
    var id: String
    var name: String
    var portfolio_url: String
    var bio: String
}

struct DataModel: Codable {
    var id: String
    var created_at: String
    var likes: Int
    var liked_by_user: Bool
    var description: String
    var urls: URLs
    var user: User
}

When decoding, just user

jsonDecoder.decode(DataModel.self, from: data)