英文:
Swift HttpSession decode arrays
问题
struct Friends: Decodable {
var friendshipid: String
var userid: String
var username: String
var pfp: String
}
英文:
I have a code to send post requests to a NestJS api. It works, but there's a request that returns the following json: (Multiplied the entrires to help understand the context)
[
{
"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"
}
]
How can i recognise it in my code? Thanks!
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???
}
答案1
得分: -1
Remove:
struct Friends: Decodable {
// how to recognise???
}
Change and add:
return try JSONDecoder().decode([T].self, from: data)
Also, you forgot to add friendshipid. And no need for ";" in the end.
struct UserData: Decodable {
var username: String
var userid: String
var pfp: String
var friendshipid: String
}
T means 1 element {element} and [T] means many elements {element1, element2}
英文:
Remove:
struct Friends: Decodable {
// how to recognise???
}
Change and add:
return try JSON Decoder().decode([T].self, from: data)
Also, you forgot to add friendshipid. And no need for ";" in the end.
struct UserData: Decodable {
var username: String
var userid: String
var pfp: String
var friendshipid: String
}
T means 1 element {element} and [T] means many elements {element1, element2}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论