Я новичок в быстром, впервые в сети в быстром использовании alamofire, и у меня было несколько проблем, я не могу разобрать вложенный JSON из моего API, прошло 3 дня, и все еще выясняю, что не так с этой проблемой, вот пример кода
API:
{
"id" : "7fc8581a0373715c62750ba2c472d5d3",
"status" : 1,
"progress" : [
{
"state" : "3",
"airline_code" : "SRI",
"data" : {
"go" : [
{
"additional" : {
"numstop" : 0
},
"flights" : [
{
"flight_num" : "SJ231",
"depart_port" : "JOG",
"depart_timezone" : "Asia/Jakarta",
"arrive_timezone" : "Asia/Jakarta",
"arrive_city" : "Jakarta, Cengkareng",
"extended_attribute" : {
"bus" : null,
"pro" : null,
"eco" : {
"id" : "6155a71e6fe687b54a97cba4de3091af",
"class_letter" : "g",
"seat_avail" : "2"
}
},
"depart_datetime" : "2018-05-05 11:00",
"id" : "bebbdb13270a448ffa55ed2e928e2d60",
"depart_city" : "Yogyakarta",
"arrive_datetime" : "2018-05-05 12:10",
"flight_duration" : "01:10",
"arrive_time" : "12:10",
"depart_time" : "11:00",
"arrive_port" : "CGK"
}
],
"id" : "0d82983e6cbcbabd9dfea57c8622253a",
"fares" : {
"bus" : null,
"pro" : null,
"eco" : {
"id" : "d06d8c19a5ad77089df538b8b54e5ac9",
"by_ages" : {
"child" : null,
"infant" : null,
"adult" : {
"basic" : 330000,
"fuel" : 0,
"discount" : 0,
"adm" : 50000,
"iwjr" : 5000,
"surcharge" : 0,
"total" : 418000,
"tax" : 33000
}
}
}
}
},
{
"additional" : {
"numstop" : 0
},
"flights" : [
{
"flight_num" : "SJ235",
"depart_port" : "JOG",
"depart_timezone" : "Asia/Jakarta",
"arrive_timezone" : "Asia/Jakarta",
"arrive_city" : "Jakarta, Cengkareng",
"extended_attribute" : {
"bus" : null,
"pro" : null,
"eco" : {
"id" : "d10c02b1fce3ef00d340faacfeebf155",
"class_letter" : "v",
"seat_avail" : "9"
}
},
"depart_datetime" : "2018-05-05 17:45",
"id" : "ad185a29a9e6b302aa6d1b86e933f029",
"depart_city" : "Yogyakarta",
"arrive_datetime" : "2018-05-05 18:55",
"flight_duration" : "01:10",
"arrive_time" : "18:55",
"depart_time" : "17:45",
"arrive_port" : "CGK"
}
],
"id" : "8dd63fa4f7256a2ac00352519ae787d6",
"fares" : {
"bus" : null,
"pro" : null,
"eco" : {
"id" : "436ab688a1e4512d41c95e55e2fdcdea",
"by_ages" : {
"child" : null,
"infant" : null,
"adult" : {
"basic" : 360000,
"fuel" : 0,
"discount" : 0,
"adm" : 50000,
"iwjr" : 5000,
"surcharge" : 0,
"total" : 451000,
"tax" : 36000
}
}
}
}
},
{
"additional" : {
"numstop" : 0
},
"flights" : [
{
"flight_num" : "IN279",
"depart_port" : "JOG",
"depart_timezone" : "Asia/Jakarta",
"arrive_timezone" : "Asia/Jakarta",
"arrive_city" : "Jakarta, Cengkareng",
"extended_attribute" : {
"bus" : {
"id" : "27bca993eb75f1ca3275f46b8229624e",
"class_letter" : "i",
"seat_avail" : "2"
},
"pro" : null,
"eco" : {
"id" : "933c24d214b8fd55d4237bf1e6eb5f6b",
"class_letter" : "g",
"seat_avail" : "3"
}
},
"depart_datetime" : "2018-05-05 19:20",
"id" : "a0c3bd5f6194975cefae8240abef8754",
"depart_city" : "Yogyakarta",
"arrive_datetime" : "2018-05-05 20:30",
"flight_duration" : "01:10",
"arrive_time" : "20:30",
"depart_time" : "19:20",
"arrive_port" : "CGK"
}
],
"id" : "614836006a92c2deac59eeaef926cf1b",
"fares" : {
"bus" : {
"id" : "865493da8066ac0c677cecfbb88e181b",
"by_ages" : {
"child" : null,
"infant" : null,
"adult" : {
"basic" : 988000,
"fuel" : 0,
"discount" : 0,
"adm" : 50000,
"iwjr" : 5000,
"surcharge" : 0,
"total" : 1141800,
"tax" : 98800
}
}
},
"pro" : null,
"eco" : {
"id" : "74802ef5e6bd5b93c016fcd98aa63925",
"by_ages" : {
"child" : null,
"infant" : null,
"adult" : {
"basic" : 330000,
"fuel" : 0,
"discount" : 0,
"adm" : 50000,
"iwjr" : 5000,
"surcharge" : 0,
"total" : 418000,
"tax" : 33000
}
}
}
}
}
]
},
"code" : null,
"message" : null,
"ctr" : "1",
"rate" : 100
}
]
}
вот мой код для его анализа:
if let json = response.result.value {
let JSONData_child = JSON(json)
let progress = JSONData_child["progress"]
print(progess)
//heres the issue
let name = progress["data"][0]["go"]["flights"].string
if name != nil {
print(name!)
}
//
}
он может получить доступ к вложенному «прогрессу», но, похоже, я не могу получить доступ к «данным» вложенному JSON
все, что мне нужно, - это получить доступ к данным о рейсах из JSON,
как я могу этого добиться?
извини, подожди, я обновлюсь
отредактировал @AnkitJayaswal

In the JSON response, date can be bundled in complex structure of
arrayanddictionary:**Array:** (Comes in the bracket `[]`) **Dictionary:** (Comes in the bracket `{}`)
Множество:
Массив имеет другое свойство для доступа к объекту. Нравиться:
Чтобы получить объекты по определенным индексам, вы можете использовать [0], [1], [2]... and so on. Также можно получить доступ к определенным индексам с first, last
Например:
let arr = [Any]()
arr.first // will give value at index 0
arr[0] // will give value of index 0
arr[1] // will give value of index 1
arr[2] // will give value of index 2
arr.last // will give value of last index
Словарь:
В словаре есть пары ключ-значение. и вы можете получить доступ к стоимости с dict["key"].
Например:
let dict = [String: Any]()
let value = dict["key"] // It will give the value for particular `key`
In your case:
Вы можете получить прямой доступ к данным, если уверены, что json не изменится. В виде:
let name = progress[0]["data"]["go"][0]["flights"][0]
Это даст словарь:
{
"flight_num" : "SJ231",
"depart_port" : "JOG",
"depart_timezone" : "Asia/Jakarta",
"arrive_timezone" : "Asia/Jakarta",
"arrive_city" : "Jakarta, Cengkareng",
"extended_attribute" : {
"bus" : null,
"pro" : null,
"eco" : {
"id" : "6155a71e6fe687b54a97cba4de3091af",
"class_letter" : "g",
"seat_avail" : "2"
}
},
"depart_datetime" : "2018-05-05 11:00",
"id" : "bebbdb13270a448ffa55ed2e928e2d60",
"depart_city" : "Yogyakarta",
"arrive_datetime" : "2018-05-05 12:10",
"flight_duration" : "01:10",
"arrive_time" : "12:10",
"depart_time" : "11:00",
"arrive_port" : "CGK"
}
кстати, что означает [0]?
эй @AnkitJayaswal
[0] извлекает элемент с индексом 0 из коллекции. это то же самое, что и myArray.first?@themasmul, я дополняю свой ответ объяснением. Просто дай мне немного времени
@AnkitJayaswal может индекс [0] / динамический? , cz Я только что получил последний полет массива.
Да [0] прямо как objectAtIndex(0). Вы можете установить [1] для первого индекса, [2], [3], [4]... и т. д.
@AnkitJayaswal как я могу зациклить индекс [0]? потому что это не динамично
@themasmul, я не понял твоей мысли. Что вы имеете в виду под loop the index?
Не удается увидеть ключ
progress