2

I am parsing a URL which is returning data in array format as below:

[
{"_id":"5bb8b6038fb09210e09fd5c6","name":"John","city":"Dallas","country":"USA","__v":0},{"_id":"5bb8b6258fb09210e09fd5c7","name":"Robert","city":"SFO","country":"USA","__v":0}
]

I have written model class as below:

class Peoples: Codable{
    let peoples:[People]
    init(peoples:[People]) {
        self.peoples = peoples
    }
}

class People: Codable{
    var _id : String
    var name : String
    var city : String
    var country : String
    var __v : Int

    init(
        _id : String,
        name : String,
        city : String,
        country : String,
        __v : Int
    )
    {
        self._id = _id
        self.name = name
        self.city = city
        self.country = country
        self.__v = __v

    }
}

And I am parsing JSON data using JSONDecoder.

class HomeTabController: UIViewController ,UITableViewDataSource,UITableViewDelegate {
    private var varPeoples= [People]()

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let url = URL(string: “<SomeURL>“)else {return}
        guard  let downloadURL = url else { return }

        URLSession.shared.dataTask(with: downloadURL) { data, urlResponse, error in
            guard let data = data, error == nil, urlResponse != nil
               else
               {
                print( "Something is wrong in URL")
                return;
               }
            print(data)
            do{
                let pplList=  JSONDecoder().decode(Peoples.self, from: data). // This line is giving data incorrect format error.
                self.varPeoples = pplList.peoples

                DispatchQueue.main.async{
                    self.tableView.reloadData()
                }
            }catch{
                print( error.localizedDescription)
            }
     }
}

If the JSON data does not have an array[] I am able to parse it. But my URL is returning data with array [] symbol. So can any one please fix the code.

0

2 Answers 2

1

The json you have is an array of People, not Peoples:

do {
    let pplList =  try JSONDecoder().decode([People].self, from: data) // This line is giving data incorrect format error.
    print("pplList =", pplList)
} catch {
    print( error.localizedDescription)
}
Sign up to request clarification or add additional context in comments.

Comments

1

The error occurs because if the root object is an array implementing an umbrella struct will break the decoding process.

Just decode the array.

Some general Decoding notes:

  • If the JSON is read-only in most cases a struct is sufficient.
  • If the JSON is read-only conforming to Decodable is sufficient.
  • If the JSON is read-only declare the struct members as constants (let).
  • It's highly recommended to add CodingKeys to transform weird keys to (more descriptive) names conforming to the Swift naming convention.
  • You don't have to write an initializer even if the object is a class, Decodable provides one.
  • To avoid singular-plural confusion name a struct in singular form (Person) and the array in plural form (people). Semantically each object in people represents one Person.
  • Never print error.localizedDescription when catching a Decoding error. localizedDescription returns a generic string but not the actual error description. Print always the entire error instance.

struct Person: Decodable {

    private enum CodingKeys: String, CodingKey { case id = "_id", name, city, country, somethingMoreDescriptiveThan__v = "__v"}

    let id : String
    let name : String
    let city : String
    let country : String
    let somethingMoreDescriptiveThan__v : Int
}

...

private var people = [Person]()

...

do {
   self.people = JSONDecoder().decode([Person].self, from: data)
   DispatchQueue.main.async{
      self.tableView.reloadData()
   }
} catch {
   print(error)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.