Swift HttpSession 解码数组

问题描述 投票:0回答:1

我有一个代码可以将发布请求发送到 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

import Foundation
func apiCall<T: Decodable>(urlString: String, body: [String:AnyHashable]) async throws -> T {
    
    guard let url = URL(string: "http://192.168.1.71:3000/\(urlString)") else { throw URLError(.badURL) }
    
    var request = URLRequest(url: url)
    // method, body, headers
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = try JSONSerialization.data(withJSONObject: body)
    
    // make rqs
    let (data, _) = try await URLSession.shared.data(for: request)
    return try JSONDecoder().decode(T.self, from: data)
}

struct IsLoggedIn: Decodable {
    var loggedin: Bool
}

struct UserData: Decodable {
    var username: String;
    var userid: String;
    var pfp: String;
}

struct Friends: Decodable {
 // how to recognise???
}
swift xcode httpsession
1个回答
0
投票

删除:

struct Friends: Decodable {
 // how to recognise???
}

更改并添加:

return try JSON Decoder().decode([T].self, from: data)

此外,您忘记添加friendshipid。并且不需要“;”最后。

struct UserData: Decodable {
  var username: String
  var userid: String
  var pfp: String
  var friendshipid: String
}

T 表示 1 个元素 {element}[T] 表示多个元素 {element1, element2}

© www.soinside.com 2019 - 2024. All rights reserved.