1

I am working receiving the following JSON file in Swift and I cant figure out how get the details elements in the JSON

[
  {
    "id": 143369,
    "history": "jd2",
    "details": [
      {
        "name": "Su 1",
        "color": "#ffffff"
      },
      {
        "name": "Stu 1",
        "color": "#ffffff"
      }
    ]
  },
  {
    "id": 143369,
    "history": "musa 2",
    "details": [
      {
        "name": "Stu 1",
        "color": "#ffffff"
      },
      {
        "name": "Stu 2",
        "color": "#ffffff"
      }
    ]
  }
]

I have created this class with which I am able to retrieve id and history but not the details. How do I include the details with the id and history?

public class students {

    let id: Int32
    let history: String?

    init(id:Int32, history:String) {
        self.id = id
        self.history = name

    }
}

Below is my web service code.

var dataArray = [students]()

    Alamofire.request(.GET, url)
        .responseJSON { response in

            if let value: AnyObject = response.result.value {

                let json = JSON(value)
                if let items = json.array {
                    for item in items {
                           self.dataArray.append(students(
                            id: item["id"].int32!,
                            history: item["history"].string!))

                            let cItems = item["details"].array
                                for citem in citems {
                                    //here
                                }
                    }
                }
            }
    }
1
  • Would you like yo use Object Mapper ? if yes then I can post an answer Commented Dec 20, 2016 at 15:04

1 Answer 1

1

your student model should be like this.

let id: Int32
let history: String?
let details: Array<[String:AnyObject]>
init(id:Int32, history:String,details:Array<[String:AnyObject]>) {
    self.id = id
    self.history = name
    self.details= details //need a cast here!
}

here is a simple parser for i used for a project to cast your Array<[String:AnyObject]> as you

func collection(data:[[String:AnyObject]]) -> [yourModel] {

        var objectArray: [yourModel] = []

        for d in data {

            let obj = yourModel(data: d as [String: AnyObject]) // i created a initializer for this object here on my project.

            objectArray.append(obj)

        }

        return objectArray

}

hope gives an idea!

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

1 Comment

Thanks, I am really new to swift and not sure of how to use this code with my existing code.

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.