Home > Net >  Swift: Get value from a JSON
Swift: Get value from a JSON

Time:05-05

I'm totally new with swift, it's my first iOs app I would like to retrieve a value from an http POST response

struct represCode: Codable{
       var CODE: String?
   }
   
   var table = [represCode]()

func httpPost(completion: @escaping (_ json: Any?)->()) {
       let json: [String: Any] = ["login": usernameText.text!.uppercased(),
                                  "pass": mdpText.text!]
       
       let urlPath = url.chaine   "login.php"
       let jsonData = try? JSONSerialization.data(withJSONObject: json)
       let url = URL(string: urlPath)!
       var request = URLRequest(url: url)

       request.httpMethod = "POST"

       // insert json data to the request
       request.httpBody = jsonData

       let task = URLSession.shared.dataTask(with: request) { data, response, error in
           guard let data = data, error == nil else {
               print(error?.localizedDescription ?? "No data")
               return
           }
           do {
               self.table = try JSONDecoder().decode([represCode].self, from: data)
               print(self.table)
               self.dl = true
               }catch _ {
                   print ("JSON Error")
           }
           completion(json)
       }
       task.resume()
     }

When I "print(self.table)" I get this

[Mobois.LoginViewController.represCode(CODE: Optional("AG"))]

And I would like to store the "AG" in a specific var (ex: var represCode: String?)

I tried many solutions that I found here but most of time I get errors like "Cannot assign value of type '[LoginViewController.represCode]' to type 'String'"

CodePudding user response:

There are two serious mistakes.

  1. The root object is an array (represented by the [] in [represCode].self)
  2. The value AG is the value for key CODE

First of all to conform to the naming convention declare the struct this way

struct RepresCode: Decodable {
    let code: String

    private enum CodingKeys: String, CodingKey { case code = "CODE" }
}

and

var table = [RepresCode]()
..
JSONDecoder().decode([RepresCode].self ...

You can access the value by getting the value for property code of the first item in the array

let represCode = table.first?.code ?? "unknown code"
  • Related