[英]How to Build a custom data model for search query and user detail using Unlash Api?
I am building an app that lets users search for photos.我正在构建一个让用户搜索照片的应用程序。 I am in the process of creating a data model using a codable.
我正在使用可编码的数据创建数据 model。 Below is the JSON data.
下面是 JSON 数据。 The data model will contain id, created_at, username, name, portfolio_url, and images.
数据 model 将包含 id、created_at、用户名、名称、portfolio_url 和图像。 How do I access the nested user and image information in the user dictionary and 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"
},
When using Codable you need to follow the hierarchy of the model.使用 Codable 时,您需要遵循 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.