Swift HttpSession解码数组

huangapple go评论79阅读模式
英文:

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}

huangapple
  • 本文由 发表于 2023年7月31日 23:42:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76805169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定