简体   繁体   中英

Parse json arrays in Swift

I'm trying to fetch some json data as follows:

[
    {
        "_id": "5ccbf88042b2f60ec690a8dd",
        "title": "Conference1",
        "description": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.",
        "cities": [
            {
                "name": "Paris",
                "numberOfUsers": "3"
            },
            {
                "name": "Marseille",
                "numberOfUsers": "7"
            },
            {
                "name": "Lyon",
                "numberOfUsers": "2"
            }
        ]
    }

    {
        "_id": "5ccbf88042b2f60ec690a8dd",
        "title": "Conference1",
        "description": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.",
        "cities": [
            {
                "name": "Paris",
                "numberOfUsers": "5"
            },
            {
                "name": "Marseille",
                "numberOfUsers": "10"
            },
            {
                "name": "Lyon",
                "numberOfUsers": "8"
            }
        ]
    }

]

Here is my code :

class Event: NSObject{

    var title: String? = ""
    var eventDescription: String? = ""
    var cities: [String:String]? = ["":""]
    var name: String? = ""
    var numberOfUsers: String? = ""


    static func parseEventData(data: Data) -> [Event] {
        var eventsArray = [Event]()

        do {
            let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)

            //Parse JSON Data
            if let events = jsonResult as? [Dictionary<String,AnyObject>] {
                for event in events {
                    let newEvent = Event()
                    newEvent.title = event["title"] as? String
                    newEvent.eventDescription = event["description"] as? String

                    newEvent.cities = event["cities"] as? [String:String]
                    for city in newEvent.cities? {
                        newEvent.name = city["name"] as? String
                        newEvent.numberOfUsers = city["numberOfUsers"] as? String
                    }



                    eventsArray.append(newEvent)
                }
            }

        }catch let err {
            print(err)
        }

        return eventsArray
    }
}

Code compiles well for title, and description but I'm stuck to catch cities correctly. Any help would be appreciated. Thank you

Correct json ( you miss a comma between array elements , )

[{
    "_id": "5ccbf88042b2f60ec690a8dd",
    "title": "Conference1",
    "description": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.",
    "cities": [{
            "name": "Paris",
            "numberOfUsers": "3"
        },
        {
            "name": "Marseille",
            "numberOfUsers": "7"
        },
        {
            "name": "Lyon",
            "numberOfUsers": "2"
        }
    ]
},
{
    "_id": "5ccbf88042b2f60ec690a8dd",
    "title": "Conference1",
    "description": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.",
    "cities": [{
            "name": "Paris",
            "numberOfUsers": "5"
        },
        {
            "name": "Marseille",
            "numberOfUsers": "10"
        },
        {
            "name": "Lyon",
            "numberOfUsers": "8"
        }
    ]
}

]

`// MARK: - Element
struct Root: Codable {
    let id, title, purpleDescription: String
    let cities: [City]

    enum CodingKeys: String, CodingKey {
        case id = "_id"
        case title
        case purpleDescription = "description"
        case cities
    }
}

// MARK: - City
struct City: Codable {
    let name, numberOfUsers: String
}

let res = try! JSONDecoder().decode([Root].self,from:data)
print(res)

Edit : here this ( cities is an array )

 newEvent.cities = event["cities"] as? [String:String]

should be

 newEvent.cities = event["cities"] as? [[String:String]]

do {
    let jsonResult = try JSONSerialization.jsonObject(with: data, options:[])

    //Parse JSON Data
    if let events = jsonResult as? [[String:Any]] {
        for event in events {
            let newEvent = Event()
            newEvent.title = event["title"] as? String
            newEvent.eventDescription = event["description"] as? String

            newEvent.cities = event["cities"] as? [[String:String]]
            for city in newEvent.cities ?? [["no city found": "number of users : 0"]] {
                newEvent.name = city["name"] ?? ""
                newEvent.numberOfUsers = city["numberOfUsers"] ?? ""
            } 
            eventsArray.append(newEvent)
        }
    }

}catch  {
    print(error)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM