Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse JSON to convert this to an array of objects in Swift?

Tags:

json

ios

swift

This is a sample of my json that is on my website:

[{
    "id": "1",
    "day": "Saturday 3/10",
    "title": "title1",
    "description": "lorem ipsum dolor sit amet consectetur adipiscing elit",
    "image": ""
},
{
    "id": "2",
    "day": "Saturday 10/10",
    "title": "title2",
    "description": "lorem ipsum dolor sit amet consectetur adipiscing elit",
    "image": ""
},
{
    "id": "3",
    "day": "Saturday 17/10",
    "title": "title3",
    "description": "lorem ipsum dolor sit amet consectetur adipiscing elit",
    "image": ""
}]

And now I want to save every object in an array of objects but it's possible that there are more than three elements. I think I have to use NSJsonSerialization because I have to get it from an url.

(I'm using swift 2)

like image 640
SeppeDev Avatar asked Dec 20 '15 22:12

SeppeDev


1 Answers

I would personally do this using NSArrays and NSDictionaries to reference each object in your JSON. Something like this should suffice (let JSON be your JSON variable)

if let array = JSON as? NSArray {
    for obj in array {
        if let dict = obj as? NSDictionary {
            // Now reference the data you need using:
            let id = dict.valueForKey("id")
        }
    }
}
like image 54
Cailean Wilkinson Avatar answered Sep 19 '22 22:09

Cailean Wilkinson