Как проанализировать JSON информацию, затем выбрать информацию и назначить ее переменной в Swift - PullRequest
0 голосов
/ 05 мая 2020

Я работаю над приложением, которое считывает публикацию c JSON о доступности велосипедов и многих других данных.

Структуры, расположенные здесь:

  struct Stations: Codable {
    let company: [String]
    let href: String
    let id: String
    let location: LocationJson
    let name: String
    let stations: [Station]

}


struct Station: Codable {
    let empty_slots: Int
    let extra: Extra
    let free_bikes: Int
    let id: String
    let latitude: Double
    let longitude: Double
    let name: String
    let timestamp: String

    public init?(empty_slots:Int, free_bikes:Int, id:String) {
        self.empty_slots = empty_slots
        self.id = id
        self.free_bikes = free_bikes

        return nil
    }

}

struct ResponseJSON: Codable {
    let network: Stations
}

struct LocationJson: Codable {
    let city: String
    let country: String
    let latitude: Double
    let longitude: Double
}


struct Extra: Codable {
    let slots: Int
    let status: String
    let uid: String

    init(slots:Int, status: String, uid: String) {
        self.slots = slots
        self.status = status
        self.uid = uid
    }

}

Естественно, все из этих станций имеет огромное количество данных. Я могу прочитать файл JSON, но не могу выбрать и использовать получаемую мной информацию. Я включаю функцию, которую написал ниже:

    func getBikeData(){
   guard let url = URL(string: "https://api.citybik.es//v2/networks/baksi-bisim")
     let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
           guard let dataResponse = data, error == nil else {
           print(error?.localizedDescription ?? "Response Error")
           return
       }
       do {
           //here dataResponse received from a network request
           let jsonResponse = try JSONSerialization.jsonObject(with:
                                  dataResponse, options: [])
           print(jsonResponse) //Response result


           do {
               //here dataResponse received from a network request
               let decoder = JSONDecoder()
               //Decode JSON Response Data

               let model = try decoder.decode(
                   ResponseJSON.self, from: dataResponse
               )
            print(model)//Output - 1221

           }
           catch let parsingError {
               print("Error", parsingError)
           }

        } catch let parsingError {
           print("Error", parsingError)
        }

   }
   task.resume()

 }

Мне действительно нужна помощь в том, как найти и назначить данные Station из JSONResponse и назначить их нужным переменным, чтобы показать метку и более полезную информацию. Как я могу реализовать эту функцию для выполнения такой задачи?

Также ниже приведен вывод:

ResponseJSON(network: MapKitTest.moreDetail.Stations(company: ["Baksi Bike Sharing System"], href: "/v2/networks/baksi-bisim", id: "baksi-bisim", location: MapKitTest.moreDetail.LocationJson(city: "Izmir", country: "TR", latitude: 38.4134047464, longitude: 27.0325753524), name: "Baksi", stations: [MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 40, status: "Active", uid: "1101"), free_bikes: 40, id: "81a2def326cc97187e41666320e38dbe", latitude: 38.4134047464, longitude: 27.0325753524, name: "İnciraltı Rekreasyon Alanı", timestamp: "2020-05-05T05:30:25.331000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 40, status: "Active", uid: "110101"), free_bikes: 40, id: "b8568b58ad34aeee55764593d36bbb71", latitude: 38.411389, longitude: 27.013472, name: "Sahilevleri 1", timestamp: "2020-05-05T05:30:25.334000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 20, status: "Active", uid: "110102"), free_bikes: 20, id: "7d33a4fccc471ee42853ed0ad74d214a", latitude: 38.406137, longitude: 26.996162, name: "Sahilevleri 2", timestamp: "2020-05-05T05:30:25.335000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 40, status: "Active", uid: "1102"), free_bikes: 40, id: "89c5c6d0e1c035629d129ed1f4acf5bc", latitude: 38.4066894063, longitude: 27.0618320135, name: "İnciraltı Kent Ormanı", timestamp: "2020-05-05T05:30:25.336000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 30, status: "Active", uid: "1103"), free_bikes: 30, id: "609f9c4238891bc09936cd7a098af35c", latitude: 38.4047512791, longitude: 27.0701936867, name: "Üçkuyular İskelesi", timestamp: "2020-05-05T05:30:25.337000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 20, status: "Active", uid: "1104"), free_bikes: 20, id: "aa2935c1ec78fc31e5c1c567efbd0594", latitude: 38.4006949388, longitude: 27.0781865266, name: "A.A Saygun", timestamp: "2020-05-05T05:30:25.339000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 30, status: "Active", uid: "1105"), free_bikes: 30, id: "183d94471151914258dea18731ff7da3", latitude: 38.3992000613, longitude: 27.0837509082, name: "Göztepe Köprü", timestamp: "2020-05-05T05:30:25.340000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 15, status: "Active", uid: "1106"), free_bikes: 15, id: "1e7f533e09a98c0b7b84a370aa4ecaa6", latitude: 38.4021639086, longitude: 27.0930261205, name: "Susuzdede", timestamp: "2020-05-05T05:30:25.341000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 15, status: "Active", uid: "1107"), free_bikes: 15, id: "44d388d823270744179416a6ac073663", latitude: 38.4062155783, longitude: 27.0987910553, name: "Köprü", timestamp: "2020-05-05T05:30:25.342000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 15, status: "Active", uid: "1108"), free_bikes: 15, id: "9cda37d23a942db3cde2af205a399fd3", latitude: 38.4090090197, longitude: 27.1089924616, name: "Karantina", timestamp: "2020-05-05T05:30:25.344000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 15, status: "Active", uid: "1109"), free_bikes: 15, id: "61b2982a8e496e2909e55e4f382fd11e", latitude: 38.4116478229, longitude: 27.1201230494, name: "Karataş", timestamp: "2020-05-05T05:30:25.345000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 38, status: "Active", uid: "1110"), free_bikes: 38, id: "b1eb2f80735902baf93de87d3474a351", latitude: 38.4187847458, longitude: 27.1264456215, name: "Konak İskele", timestamp: "2020-05-05T05:30:25.346000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 20, status: "Active", uid: "111001"), free_bikes: 20, id: "c4cd8015779e1633d8dd8e8792abb1c3", latitude: 38.416539, longitude: 27.127547, name: "Konak Metro ", timestamp: "2020-05-05T05:30:25.347000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 20, status: "Active", uid: "1111"), free_bikes: 20, id: "11d0c49d801d6f4bffd986c8e759e3c4", latitude: 38.4275173482, longitude: 27.1325844103, name: "Pasaport İskele", timestamp: "2020-05-05T05:30:25.348000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 20, status: "Active", uid: "1112"), free_bikes: 20, id: "147af47ab155d7630fa0d6318794c886", latitude: 38.4303211039, longitude: 27.1342384751, name: "Vasıf Çınar", timestamp: "2020-05-05T05:30:25.349000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 12, status: "Active", uid: "1113"), free_bikes: 12, id: "99ba54bf2aa81d0fad7fea5a3e1dc7e7", latitude: 38.4340526994, longitude: 27.1380971058, name: "Ali Çetinkaya Bulvarı", timestamp: "2020-05-05T05:30:25.351000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 21, status: "Active", uid: "1114"), free_bikes: 21, id: "a282e085c85c42f5dc6d37cd2a41e239", latitude: 38.4384639223, longitude: 27.1414140426, name: "Alsancak İskele", timestamp: "2020-05-05T05:30:25.352000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 12, status: "Active", uid: "1115"), free_bikes: 12, id: "d3b95b4926f1c641cc3e726555cdea6c", latitude: 38.4421949873, longitude: 27.1432792183, name: "Liman", timestamp: "2020-05-05T05:30:25.353000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 15, status: "Active", uid: "1116"), free_bikes: 15, id: "8ea919ee44cc8a8b9c21c78241b6f90b", latitude: 38.439948857, longitude: 27.1478470394, name: "Alsancak Garı", timestamp: "2020-05-05T05:30:25.354000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 22, status: "Active", uid: "1117"), free_bikes: 22, id: "678444256ec651a9ec27796473f4dbc7", latitude: 38.4451831829, longitude: 27.1707578568, name: "Meles Rekreasyon Alanı", timestamp: "2020-05-05T05:30:25.359000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 20, status: "Active", uid: "111701"), free_bikes: 20, id: "0dc0e46284e114af08922a0de6b2fe9c", latitude: 38.468382, longitude: 27.211666, name: "Buz Pisti 1", timestamp: "2020-05-05T05:30:25.360000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 15, status: "Active", uid: "1118"), free_bikes: 15, id: "36e009dd4f4a2e174c9ad794cccb0304", latitude: 38.4635758915, longitude: 27.1627288532, name: "Bayraklı İskele", timestamp: "2020-05-05T05:30:25.362000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 12, status: "Active", uid: "1119"), free_bikes: 12, id: "73df94d74b8e9010f7326b1a3e40eb75", latitude: 38.4667637722, longitude: 27.158891294, name: "Bayraklı Nikah Salonu", timestamp: "2020-05-05T05:30:25.363000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 12, status: "Active", uid: "1120"), free_bikes: 12, id: "570ff88190f008480dc00eeab22b7581", latitude: 38.4671289884, longitude: 27.1495805948, name: "İzban Turan İstasyonu", timestamp: "2020-05-05T05:30:25.365000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 3, status: "Active", uid: "1122"), free_bikes: 3, id: "36da158bb8190f739ba73da40eab4b95", latitude: 38.4552765126, longitude: 27.120318845, name: "Karşıyaka iskele", timestamp: "2020-05-05T05:30:25.368000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 12, status: "Active", uid: "1123"), free_bikes: 12, id: "3aa1d333fb31ec7ba88526aee7f899f9", latitude: 38.4494793514, longitude: 27.1105867977, name: "Karşıyaka Evlendirme Dairesi", timestamp: "2020-05-05T05:30:25.369000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 12, status: "Active", uid: "1124"), free_bikes: 12, id: "11d48f2f7823aa3f21c8f36b78c7fe20", latitude: 38.4511789658, longitude: 27.1041118947, name: "Yunuslar", timestamp: "2020-05-05T05:30:25.370000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 12, status: "Active", uid: "1125"), free_bikes: 12, id: "ad4e0f95996a8a20fd68cbafe8db408b", latitude: 38.45471, longitude: 27.096761, name: "Bostanlı iskele ", timestamp: "2020-05-05T05:30:25.371000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 24, status: "Active", uid: "1126"), free_bikes: 24, id: "d6353dd7ab8c3ca0f4e4d002c437e382", latitude: 38.456065695, longitude: 27.0926334293, name: "Bostanlı Odağı", timestamp: "2020-05-05T05:30:25.372000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 40, status: "Active", uid: "1127"), free_bikes: 40, id: "3c6f736309838b74754c0625ca2ce3d7", latitude: 38.4622502557, longitude: 27.0849728096, name: "Bostanlı Spor Tesisleri", timestamp: "2020-05-05T05:30:25.373000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 12, status: "Active", uid: "1128"), free_bikes: 12, id: "914e4271e4747ad8a12539cd320a3f5f", latitude: 38.465435, longitude: 27.0817107, name: "Mavişehir Balıkçı Barınağı", timestamp: "2020-05-05T05:30:25.374000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 8, status: "Active", uid: "1129"), free_bikes: 8, id: "eaf112af663ad0ad37c3863fa703594f", latitude: 38.4674834, longitude: 27.0793412, name: "Mavişehir", timestamp: "2020-05-05T05:30:25.376000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 30, status: "Active", uid: "1131"), free_bikes: 30, id: "415ca0c2cf9cf73b30db66b7a25990ef", latitude: 38.533134, longitude: 26.898589, name: "Kuş Cenneti", timestamp: "2020-05-05T05:30:25.378000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 24, status: "Active", uid: "1132"), free_bikes: 24, id: "fb7ea8f96edb19733d2807294a470662", latitude: 38.487952, longitude: 26.958984, name: "Doğal Yaşam Parkı", timestamp: "2020-05-05T05:30:25.379000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 12, status: "Active", uid: "1121"), free_bikes: 12, id: "62686b23d8531f66f204487ec2500c6a", latitude: 38.460954, longitude: 27.127738, name: "Alaybey Tersane Cafe", timestamp: "2020-05-05T05:30:25.366000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 20, status: "Active", uid: "111702"), free_bikes: 20, id: "5abb28cac806012786d90efd4f5b31d0", latitude: 38.46576, longitude: 27.207689, name: "Buz Pisti 2", timestamp: "2020-05-05T05:30:25.361000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 15, status: "Active", uid: "111605"), free_bikes: 15, id: "55ca65e3f8c19fe8bc06cb1c6759a21f", latitude: 38.424372, longitude: 27.143219, name: "Fuar Basmane", timestamp: "2020-05-05T05:30:25.358000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 15, status: "Active", uid: "111603"), free_bikes: 15, id: "ac286589d8a8178f2c52d2f15889d338", latitude: 38.42975, longitude: 27.142266, name: "Fuar Lozan", timestamp: "2020-05-05T05:30:25.355000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 15, status: "Active", uid: "111604"), free_bikes: 15, id: "77c9cfeeefb97b24adbf92992dfc6bc8", latitude: 38.427879, longitude: 27.14175, name: "Fuar Montrö", timestamp: "2020-05-05T05:30:25.356000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 12, status: "Active", uid: "1130"), free_bikes: 12, id: "ac93bdd032b07712b7d5ba8b5437a972", latitude: 38.4749864, longitude: 27.0747371, name: "Mavi Bahçe", timestamp: "2020-05-05T05:30:25.377000Z"), MapKitTest.moreDetail.Station(empty_slots: 0, extra: MapKitTest.moreDetail.Extra(slots: 0, status: "Active", uid: "1300"), free_bikes: 0, id: "c4311294e7ce99c966cc9ae4f0259fd1", latitude: 38.4187094, longitude: 27.1250995, name: "Bisim Üye Noktası", timestamp: "2020-05-05T05:30:25.382000Z")]))

Ответы [ 2 ]

1 голос
/ 05 мая 2020
Alamofire.request("https://api.citybik.es//v2/networks/baksi-bisim").responseJSON { json in 
/// do what you want with your JSON e.g 
let stationName = json["network"][0]["name"].string ?? ""
}

ИЛИ

let json = JSON(data: dataFromNetworking)
if let stationName = json["network"][0]["name"].string {
  // Now you got your value
}
1 голос
/ 05 мая 2020

Вот как вы можете продолжить.

Предположим, вы хотите получить stationName из stations массива,

let stationName = "A.A Saygun"

Теперь вы можете использовать first(_:) в массиве stations для получить соответствующий экземпляр Station,

let model = try JSONDecoder().decode(ResponseJSON.self, from: data)
if let station = model.network.stations.first(where: { $0.name == stationName }) {
    //get the properties of station here as per requirement
    let emptySlots = station.emptySlots
    let freeBikes = station.freeBikes
    let status = station.extra.status
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...