如何从JSON创建对象集合

时间:2018-08-24 10:41:54

标签: ios json swift class object

我正在学习Swift,并且想开发一个可以在地图上显示公交车GPS坐标的应用程序。总线lat和lon来自JSON(以下摘录):

    {
   "result":[
      {
         "Lat":52.276408,
         "Lon":21.167618,
         "Time":"2018-08-24 11:50:05",
         "Lines":"225",
         "Brigade":"4"
      },
      {
         "Lat":52.222656,
         "Lon":21.102633,
         "Time":"2018-08-24 11:51:03",
         "Lines":"225",
         "Brigade":"2"
      },
      {
         "Lat":52.2100185,
         "Lon":21.2054211,
         "Time":"2018-08-24 11:51:08",
         "Lines":"119",
         "Brigade":"2"
      },
      {
         "Lat":52.1676735,
         "Lon":21.2222606,
         "Time":"2018-08-24 11:51:07",
         "Lines":"213",
         "Brigade":"3"
      }
    ]
}

我当时正在考虑创建Bus类

class Bus {

    var latitude : Double = 1.11
    var longitude : Double = 2.22
    var lines : Int = 0

    init (lat: Double, lon: Double, line: Int) {

        latitude = lat
        longitude = lon
        lines = line

    }   
}

但是我试图弄清楚如何从JSON创建这些总线对象的集合,该JSON(全部)包含大约1000个对象(一天中的数量各不相同)。

有人能指出我正确的方向吗?我不需要完全编码的解决方案,仅需要一些有关如何实现此目标的指示。

我很可能会使用SwiftyJSON CocoaPod进行JSON解析,并使用Alamofire进行获取。

谢谢!

3 个答案:

答案 0 :(得分:0)

您可以按照评论中的 Larme 的方式使用Under Codable类。

import Foundation

class MyModelClass: Codable {
    let result: [Result]

    init(result: [Result]) {
        self.result = result
    }
}

class Result: Codable {
    let lat, lon: Double
    let time, lines, brigade: String

    enum CodingKeys: String, CodingKey {
        case lat = "Lat"
        case lon = "Lon"
        case time = "Time"
        case lines = "Lines"
        case brigade = "Brigade"
    }

    init(lat: Double, lon: Double, time: String, lines: String, brigade: String) {
        self.lat = lat
        self.lon = lon
        self.time = time
        self.lines = lines
        self.brigade = brigade
    }
}

如果您想使用ObjectMapper,则可以使用下面的类

import Foundation 
import ObjectMapper 

class MyModelClass: Mappable { 

    var result: [Result]? 

    required init?(map: Map){ 
    } 

    func mapping(map: Map) {
        result <- map["result"] 
    }
} 

class Result: Mappable { 

    var lat: NSNumber? 
    var lon: NSNumber? 
    var time: String? 
    var lines: String? 
    var brigade: String? 

    required init?(map: Map){ 
    } 

    func mapping(map: Map) {
        lat <- map["Lat"] 
        lon <- map["Lon"] 
        time <- map["Time"] 
        lines <- map["Lines"] 
        brigade <- map["Brigade"] 
    }
} 

答案 1 :(得分:0)

像这样编写列表模型

class BusListModel {

var list = [Bus]()
var longitude : Double = 2.22
var lines : Int = 0

   init (With dict:[String:Any]) {
       if let result = dict["result"] as? [[String:Any]]{
           for busDetail in result{
            let model = Bus(lat: **valueHere**, lon: **valueHere**, line: **valueHere**)
             list.append(model)
            }

         }
   }   
}

答案 2 :(得分:0)

谢谢大家的回答,尤其是@dahiya_boy

我定制了@dahiya_boy发布的代码,最终得到了我真正需要的代码。

下面是代码。我出于示例目的创建了jsonString

import Foundation

    class MyModelClass: Codable {
        let busArray: [Bus]

        enum CodingKeys: String, CodingKey {
            case busArray = "result"
        }

        init(busArray: [Bus]) {
            self.busArray = busArray
        }
    }

    class Bus: Codable {
        let lat, lon: Double
        let time, lines, brigade: String

        enum CodingKeys: String, CodingKey {
            case lat = "Lat"
            case lon = "Lon"
            case time = "Time"
            case lines = "Lines"
            case brigade = "Brigade"
        }

        init(lat: Double, lon: Double, time: String, lines: String, brigade: String) {
            self.lat = lat
            self.lon = lon
            self.time = time
            self.lines = lines
            self.brigade = brigade
        }
    }

    var jsonString = """

    {
    "result":[
    {
    "Lat":52.276408,
    "Lon":21.167618,
    "Time":"2018-08-24 11:50:05",
    "Lines":"225",
    "Brigade":"4"
    },
    {
    "Lat":52.222656,
    "Lon":21.102633,
    "Time":"2018-08-24 11:51:03",
    "Lines":"225",
    "Brigade":"2"
    },
    {
    "Lat":52.2100185,
    "Lon":21.2054211,
    "Time":"2018-08-24 11:51:08",
    "Lines":"119",
    "Brigade":"2"
    },
    {
    "Lat":52.1676735,
    "Lon":21.2222606,
    "Time":"2018-08-24 11:51:07",
    "Lines":"213",
    "Brigade":"3"
    }
    ]
    }

    """

    if let jsonData = jsonString.data(using: .utf8) {

        let decodedJSON = try! JSONDecoder().decode(MyModelClass.self, from: jsonData)

        print("Latitude: \(decodedJSON.busArray[0].lat), Longitude: \(decodedJSON.busArray[0].lon), Line: \(decodedJSON.busArray[0].lines)")

    }

这将打印以下控制台输出:

Latitude: 52.276408, Longitude: 21.167618, Line: 225