0

How can I parse JSON to a class when JSON has multiples arrays? I'm trying to convert data from REST API to my classes in Swift 2.0, but I can't figure out how to do it properly, anyone can help?

/* JSON from REST API
{
  "Name": "New name",
  "Email": "[email protected]",
  "FacebookId": "new facebook Id",
  "Address": "New Address",
  "Photo": "https://graph.facebook.com/novo facebook Id/picture?width=500&height=500",
  "CreditCards": [
    {
      "Id": 5,
      "LastNumber": "3123",
      "Brand": "visa"
    },
    {
      "Id": 6,
      "LastNumber": "3124",
      "Brand": "visa"
    }
  ]
}

Class representation in swift?

    class Client {
  var fullName: String?
  var email: String?
  var facebookId: String?
  var photo: String?
  var creditCards: [CreditCard]?

  required init(json: JSON) {
    self.fullName = json["FullName"].string
    self.email = json["Email"].string
    self.facebookId = json["FacebookId"].string
    self.photo = json["Photo"].string
    self.creditCards = json["CreditCards"]["Id"]
  }

  required init() {}
}

class CreditCard {
  var Id: Int?
  var lastNumber: String?
  var brand: String?
}

1 Answer 1

1

You should take a look at the NSJSONSerialization class and its methods. They do exactly what you need: converting JSON data into arrays, dictionaries, strings and numbers.

Sign up to request clarification or add additional context in comments.

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.