代码之家  ›  专栏  ›  技术社区  ›  Jordi Gallen Renau

Swift 3-将模拟JSON声明为来自服务器的响应

  •  2
  • Jordi Gallen Renau  · 技术社区  · 7 年前

    Error declaring Simulated JSON

    这是我必须映射JSON的三个模型,当它来自服务器时,或者在本例中是模拟的JSON。

    第一种是“LegendEntriesModel”:

    import Foundation
    import ObjectMapper
    import AlamofireDomain
    
    class LegendEntriesModel: Mappable {
    
    
    fileprivate var _id_snapshot:     String?
    fileprivate var _date:            String?
    fileprivate var _deliverables:    [DeliverablesModel]?
    
    
    
    init(){}
    
    required init?(map: Map) { }
    
    func mapping(map: Map) {
        self.id_snapshot      <- map["id_snapshot"]
        self.date             <- map["date"]
        self.deliverables     <- map["deliverables"]
    }
    
    var id_snapshot: String {
        get {
            if _id_snapshot == "" {
                _id_snapshot = ""
            }
            return _id_snapshot!
        }
        set {
            _id_snapshot = newValue
        }
    }
    
    
    var date: String {
        get {
            if _date == "" {
                _date = ""
            }
            return _date!
        }
        set {
            _date = newValue
        }
    }
    
    
    var deliverables: [DeliverablesModel] {
        get {
            if _deliverables == nil {
                _deliverables = []
            }
            return _deliverables!
        }
        set {
            _deliverables = newValue
        }
    }
    
    
    
    //MARK: RELEASE MEMORY BETWEEN OBJECT AND API REST (BROKE DEPENDENCIS)
    func copy()->LegendEntriesModel {
    
        let legendEntriesModel  = LegendEntriesModel()
    
        legendEntriesModel.id_snapshot   = self.id_snapshot
        legendEntriesModel.date          = self.date
        legendEntriesModel.deliverables  = copyDeliverables()
    
        return legendEntriesModel
    }
    
    func copyDeliverables() -> [DeliverablesModel]{
        var newArray: [DeliverablesModel] = []
        for item in deliverables {
            newArray.append(item.copy())
        }
        return newArray
    }
    }
    

    import Foundation
    import ObjectMapper
    import AlamofireDomain
    
    class DeliverablesModel: Mappable {
    
    
    fileprivate var _id:              String?
    fileprivate var _type:            String?
    fileprivate var _url_layer:       String?
    fileprivate var _options:         OptionsDeliverablesModel?
    
    
    
    init(){}
    
    required init?(map: Map) { }
    
    func mapping(map: Map) {
        self.id               <- map["id"]
        self.type             <- map["type"]
        self.url_layer        <- map["url_layer"]
        self.options          <- map["options"]
    }
    
    var id: String {
        get {
            if _id == "" {
                _id = ""
            }
            return _id!
        }
        set {
            _id = newValue
        }
    }
    
    
    var type: String {
        get {
            if _type == "" {
                _type = ""
            }
            return _type!
        }
        set {
            _type = newValue
        }
    }
    
    
    var url_layer: String {
        get {
            if _url_layer == "" {
                _url_layer = ""
            }
            return _url_layer!
        }
        set {
            _url_layer = newValue
        }
    }
    
    var options: OptionsDeliverablesModel {
        get {
            if _options == nil {
                _options = OptionsDeliverablesModel()
            }
            return _options!
        }
        set {
            _options = newValue
        }
    }
    
    //MARK: RELEASE MEMORY BETWEEN OBJECT AND API REST (BROKE DEPENDENCIS)
    func copy()->DeliverablesModel {
    
        let deliverablesModel  = DeliverablesModel()
    
        deliverablesModel.id         = self.id
        deliverablesModel.type       = self.type
        deliverablesModel.url_layer  = self.url_layer
        deliverablesModel.options    = self.options
    
        return deliverablesModel
    }
    }
    

    最后一个是“OptionsDeliverablesModel”:

    import Foundation
    import ObjectMapper
    import AlamofireDomain
    
    class OptionsDeliverablesModel: Mappable {
    
    
    fileprivate var _type:                 String?
    fileprivate var _max_range:            Float?
    fileprivate var _min_range:            Float?
    fileprivate var _title:                String?
    fileprivate var _initial_max_value:    Float?
    fileprivate var _initial_min_value:    Float?
    fileprivate var _id:                   String?
    
    
    
    init(){}
    
    required init?(map: Map) { }
    
    func mapping(map: Map) {
        self.type                       <- map["type"]
        self.max_range                  <- map["max_range"]
        self.min_range                  <- map["min_range"]
        self.title                      <- map["title"]
        self.initial_max_value          <- map["initial_max_value"]
        self.initial_min_value          <- map["initial_min_value"]
        self.id                         <- map["id"]
    }
    
    var type: String {
        get {
            if _type == "" {
                _type = ""
            }
            return _type!
        }
        set {
            _type = newValue
        }
    }
    
    
    var max_range: Float {
        get {
            if _max_range == 0 {
                _max_range = 0
            }
            return _max_range!
        }
        set {
            _max_range = newValue
        }
    }
    
    var min_range: Float {
        get {
            if _min_range == 0 {
                _min_range = 0
            }
            return _min_range!
        }
        set {
            _min_range = newValue
        }
    }
    
    
    var title: String {
        get {
            if _title == "" {
                _title = ""
            }
            return _title!
        }
        set {
            _title = newValue
        }
    }
    
    var initial_max_value: Float {
        get {
            if _initial_max_value == 0 {
                _initial_max_value = 0
            }
            return _initial_max_value!
        }
        set {
            _initial_max_value = newValue
        }
    }
    
    var initial_min_value: Float {
        get {
            if _initial_min_value == 0 {
                _initial_min_value = 0
            }
            return _initial_min_value!
        }
        set {
            _initial_min_value = newValue
        }
    }
    
    var id: String {
        get {
            if _id == "" {
                _id = ""
            }
            return _id!
        }
        set {
            _id = newValue
        }
    }
    
    
    
    
    //MARK: RELEASE MEMORY BETWEEN OBJECT AND API REST (BROKE DEPENDENCIS)
    func copy()->OptionsDeliverablesModel {
    
        let optionsDeliverablesModel  = OptionsDeliverablesModel()
    
        optionsDeliverablesModel.type               = self.type
        optionsDeliverablesModel.max_range          = self.max_range
        optionsDeliverablesModel.min_range          = self.min_range
        optionsDeliverablesModel.title              = self.title
        optionsDeliverablesModel.initial_max_value  = self.initial_max_value
        optionsDeliverablesModel.initial_min_value  = self.initial_min_value
        optionsDeliverablesModel.id                 = self.id
    
        return optionsDeliverablesModel
    }
    }
    

    有了这三个“模型”,我可以在类DAO内映射JSON,但问题是,因为我不知道如何传递我模拟的JSON。

    import AlamofireDomain
    import Alamofire
    import ObjectMapper
    
    class DeliverablesLegendDAO : SimpleDAO {
    
    var deliverables = Dictionary<String, Any>()
    
    deliverables = [{"legendEntries": [{"id_snapshot": "123","date": "2016-10-20","deliveries": [{"id": "12","type": "RGB","url_layer":"topp:states","options": [{"type": "range","max_range": 100,"min_range": 0,"title": "Option RGB","initial_max_value": 100,"initial_min_value": 0,"id": "depth"}]}]}]}]
    
    func snapshots(_ parameters: String,
               callbackFuncionOK:    @escaping (LegendEntriesModel)->(),
               callbackFunctionERROR: @escaping (Int,NSError)->()) {
    
    
    
        Alamofire.request(parameters,
                          method: .post,
                          encoding: JSONEncoding.default)
            .responseJSON { response in
                if response.result.isSuccess{
                    if let status = response.response?.statusCode {
                        switch(status){
                        case 200:
                            let value = response
                            let legendEntries = Mapper<LegendEntriesModel>().map(JSONObject: value)
                            callbackFuncionOK(legendEntries!)
    
                        default:
                            break
                        }
                    }
                }
    
                else {
                    var statusCode = -1
                    if let _response = response.response {
                        statusCode = _response.statusCode
                    }
                    var nsError: NSError = NSError(domain: Constants.UNKNOWN_HTTP_ERROR_MSG,
                                                   code: Constants.UNKNOWN_HTTP_ERROR_ID,
                                                   userInfo: nil)
                    if let _error = response.result.error {
                        nsError = _error as NSError
                    }
                    callbackFunctionERROR(statusCode,nsError)
                }
    
        }
    }
    
    }
    

    如图所示,我声明我的模拟JSON错误,然后用“LegendDeliveriesModel”将其映射到一个对象。我该怎么做?

    Error declaring simulated JSON

    如果您还需要什么,请告诉我。我重复一遍,问题在于JSON模拟语句中我不知道如何将其传递给DAO,并且它映射了它。

    2 回复  |  直到 7 年前
        1
  •  5
  •   FreeGor omz    6 年前

    func loadJsonFrom(fileName: String) -> NSDictionary {
    
        let path = Bundle.main.path(forResource: filename, ofType: "json")
        let jsonData = try! Data(contentsOf: URL(fileURLWithPath: path!))
        let jsonResult: NSDictionary = try! JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as! NSDictionary
        return jsonResult
    }
    
        2
  •  1
  •   user2877496    7 年前

    我认为您声明JSON的语法是错误的。可以肯定的是,在swift中内联声明词典时,您只使用[“key”:“value”]

    编辑:对不起,我没有意识到这超出了一种方法。如果你想这样做,你必须这样直接申报

        var deliverables = ["legendEntries": ["id_snapshot": "123","date": "2016-10-20","deliveries": ["id": "12","type": "RGB","url_layer":"topp:states","options": ["type": "range","max_range": 100,"min_range": 0,"title": "Option RGB","initial_max_value": 100,"initial_min_value": 0,"id": "depth"]]]]
    

    如果只是将其用作模拟数据,我也会考虑将其设置为let常量,而不是变量