Разбор массивов json в Swift - PullRequest
0 голосов
/ 03 июня 2019

Я пытаюсь получить некоторые данные JSON следующим образом:

[
    {
        "_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"
            }
        ]
    }

]

Вот мой код:

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
    }
}

Код хорошо компилируется для заголовка и описания, но япопробую ловить города правильно.Любая помощь будет оценена.Спасибо

1 Ответ

1 голос
/ 03 июня 2019

Правильный json (вы пропускаете запятую между элементами массива ,)

[{
    "_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)

Редактировать : здесьэто (города это массив)

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

должно быть

 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)
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...