SwiftUI class Codable

Hello,

I’m having a little issue with my Codable class…
I have an Int which I will Post on my API. But when I get it back, it is a String.
Let me show you some code:

  • this is my class:
class NFCDataSec: ObservableObject, Codable {
    enum CodingKeys: String, CodingKey {
        case firstName, lastName, age, height, weight
    }
    @Published var lastName: String = ""
    @Published var firstName: String = ""
    @Published var age: Int = 0
    @Published var height: Int = 0
    @Published var weight: Int = 0

    init() {    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        lastName = try container.decode(String.self, forKey: .lastName)
        firstName = try container.decode(String.self, forKey: .firstName)
        age = try container.decode(Int.self, forKey: .age) // (1)
        height = try container.decode(Int.self, forKey: .height) // (1)
        weight = try container.decode(Int.self, forKey: .weight) // (1)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(firstName, forKey: .firstName)
        try container.encode(lastName, forKey: .lastName)
        try container.encode(age, forKey: .age)
        try container.encode(height, forKey: .height)
        try container.encode(weight, forKey: .weight)
    }
}
  • this is my JSON Post request:
            guard let encoded = try? JSONEncoder().encode(dataToWrite) else {
                print("Fail to encode SecuringData - NFCDataSec")
                return
            }
            let url = URL(string: "https://MY_API.COM/api/sendToChip")!
            var request = URLRequest(url: url)
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.httpMethod = "POST"
            request.httpBody = encoded

            URLSession.shared.dataTask(with: request) { data, res, error in
                guard let httpResponse = res as? HTTPURLResponse,
                        (200...299).contains(httpResponse.statusCode) else {
                        self.handleServerError(res)
                    return
                }
                if let data = data {
                    let decoder = JSONDecoder()
                    if let json = try? decoder.decode(NFCDataSec.self, from: data) {
                        print(json)
                    }
                    else {
                        let dataString = String(decoding: data, as: UTF8.self)
                        print("Invalid response \(dataString)") // (2)
                    }
                }
            }.resume()

(1) the API GET returns String instead of Int - but it needs to have Int when I’m making the POST method
(2) I get an invalid response from the API when I GET the data back from it.

This topic was automatically closed after 166 days. New replies are no longer allowed.