-4

I need help to read json in ios swift. I know i can use decodable but this is an exemple of my json. When i try xith decodable, i always get a nil variable.

Thnaks for your help

[
     {
       "name": "Bob",
       "age": "16",
       "employed": "No"
     },
     {
       "name": "Vinny",
       "age": "56",
       "employed": "Yes"
     }
]

This is my code, with decodable

struct personResult: Decodable{
    var person: [Person]
}

struct Person:Decodable{
    var name: String
    var age: String
    var employed: String
}

and This is my function

    
    func getJson() {
      let url = URL(string: myUrl)!

      let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
        if let error = error {
          print("Error : \(error)")
          return
        }
        
        guard let httpResponse = response as? HTTPURLResponse,
              (200...299).contains(httpResponse.statusCode) else {
          print("Error with the response, unexpected status code: \(response)")
          return
        }
        
        if let data = data {
            
            print(data)
            do {
                let result = try JSONDecoder().decode(personResult.self, from: data)
                print(result)

                
            }catch _ {
                print("errror during json decoder")
            }
            
        }
      })
      task.resume()
    }
    
    
    
}

I always enter on my catch, and printed error message

Alberto
  • 1
  • 1
  • 1
    post what you have tried – Shehata Gamal Apr 22 '21 at 13:20
  • "When i try xith decodable, i always get a nil variable." And what's your code when this happens? Do you property do a do/try/catch, so you have a meaningful error? Or it's nil because you are missing some async concept? – Larme Apr 22 '21 at 13:20
  • have you tried to decode it as an Array ? – Marwen Doukh Apr 22 '21 at 13:20
  • @Goju First of all please add `catch let error` and print that error to see what went wrong. Secondly, why there is a person key? It is not in the json above. If there is no person key in your `JSON`, just replace `personResult.self` with `[Person].self`. – Rob Apr 22 '21 at 13:37
  • @Rob Thanks for your help, with [Person].self it's work ! – Alberto Apr 22 '21 at 13:41
  • @Goju Re-read my comment above again. I have mentioned the solution too. – Rob Apr 22 '21 at 13:42
  • let result = try JSONDecoder().decode([Person].self, from: data) – El Tomato Apr 22 '21 at 14:21

1 Answers1

1

You JSON is an Array and not a Dictionary, just you the Person struct

struct Person:Decodable{
var name: String
var age: String
var employed: String
}

Then in the function:

func getJson() {
  let url = URL(string: myUrl)!

  let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
    if let error = error {
      print("Error : \(error)")
      return
    }
    
    guard let httpResponse = response as? HTTPURLResponse,
          (200...299).contains(httpResponse.statusCode) else {
      print("Error with the response, unexpected status code: \(response)")
      return
    }
    
    if let data = data {
        
        print(data)
        do {
            let result = try JSONDecoder().decode([Person].self, from: data)
            print(result)

            
        }catch let error {
            print(error)
        }
        
    }
  })
  task.resume()
}
}
Rob
  • 2,086
  • 18
  • 25