【问题标题】:How to Build a custom data model for search query and user detail using Unlash Api?如何使用 Unlash Api 为搜索查询和用户详细信息构建自定义数据模型?
【发布时间】:2021-02-05 05:57:59
【问题描述】:

我正在构建一个允许用户搜索照片的应用。我正在使用可编码的数据模型创建数据模型。下面是 JSON 数据。数据模型将包含 id、created_at、username、name、portfolio_url 和 images。如何访问用户字典和 URL 图像中的嵌套用户和图像信息。

 {
        "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"
          },

【问题讨论】:

    标签: ios swift uitableview codable jsonmodel


    【解决方案1】:

    使用 Codable 时,您需要遵循模型的层次结构。

    使用三个结构或类作为:

    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
    }
    

    解码时,只是用户

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 1970-01-01
      • 2012-10-10
      • 2022-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多