Swift中URLSession解码NestJS API返回的数组JSON方法
如何在Swift中解码NestJS API返回的数组格式JSON
你的NestJS API返回的是包含多个好友条目数组格式的JSON:
[ { "friendshipid": "64ad04f03e3afbddb87f2c82", "userid": "64ad04c53e3afbddb87f2c26", "username": "Alms2", "pfp": "http://localhost:3000/CDN//pfp/default.png" }, { "friendshipid": "64ad04f03e3afbddb87f2c82", "userid": "64ad04c53e3afbddb87f2c26", "username": "Alms2", "pfp": "http://localhost:3000/CDN//pfp/default.png" } ]
结合你现有的HttpPOST.swift代码,按以下步骤实现解码:
步骤1:定义单个好友条目的结构体
创建对应JSON数组中单个元素的结构体,包含所有字段并遵循Decodable协议:
struct Friend: Decodable { let friendshipid: String let userid: String let username: String let pfp: String }
步骤2:直接解码为数组类型
你的apiCall函数支持泛型Decodable类型,而Swift的数组[T]本身也遵循Decodable(只要T遵循),所以调用时直接指定泛型为[Friend]即可:
// 示例调用 do { let friends: [Friend] = try await apiCall( urlString: "你的好友列表接口路径", body: ["请求体参数": "对应值"] ) // 遍历或处理friends数组 for friend in friends { print("用户名:\(friend.username),用户ID:\(friend.userid)") } } catch { print("解码或请求错误:\(error)") }
关于你定义的Friends结构体
如果一定要保留Friends结构体作为数组的包装,只有当API返回对象包裹数组(比如{"friends": [数组元素]})时才需要。但你的API直接返回数组,所以不需要额外定义Friends结构体,直接使用[Friend]更简洁。
内容的提问来源于stack exchange,提问作者Alms
相关产品推荐
相关产品推荐

