【问题标题】:How to map multi-dimensional array of JSON response with Alamofire+ObjectMapper?如何使用 Alamofire+ObjectMapper 映射 JSON 响应的多维数组?
【发布时间】:2018-03-28 23:31:18
【问题描述】:

我正在尝试使用 Alamofire+ObjectMapper 开始我的项目。

我可以使用对象数组(使用键)进行简单映射。

但是,这是必须的情况,我必须使用以下 JSON 格式,它有一些问题:

1:非常嵌套的数组(3维)

2:每一层的数组没有key

所以我不能像 JSON 所代表的那样创建对象。请帮忙!!


我的 JSON 字典:

{
  "structure_model": [
        [
            [
                {
                    "test": "test"
                }
            ]
        ]
    ]
}

我的模型:

class Component: Mappable, Codable {
    var test : String = ""
    required init?(map: Map) {
        
    }
    
    func mapping(map: Map) {
        test <- map["test"]
    }
    
    
}

class StructureModel: Mappable, Codable {
    
    var structureModels :    [Array<Array<Component>>]?
    
    required init?(map: Map){
        
    }
    
    func mapping(map: Map) {
        structureModels   <- map["structure_model"]
    }
}

我做了什么:

Alamofire.request(API, method: .post, parameters: parameters, encoding: JSONEncoding.default).validate().responseObject { (response: DataResponse<StructureModel>) in etc... }

我希望是这样的:

structureModels = [ 
  [
    [Component, Component, ...], 
    [Component, Component, ...],
    ...
  ] ,
  [ 
    [Component, Component, ...], 
    [Component, Component, ...], 
    ...
  ] ,
  ...]

我得到了什么:

structureModels = nil

【问题讨论】:

  • 也许这会给你一些想法:github.com/Hearst-DD/ObjectMapper/issues/626
  • 一个建议是不要使用 AlamofireObjectMapper(您似乎在使用),而是尝试在收到 responseJSON 的响应时手动预解析您的 JSON。
  • @Hexfire 谢谢你的回复!!我在 github 上检查了这个问题,但它没有帮助,因为 JSON 的结构不同,我仍然不知道如何处理我的 JSON。
  • @Hexfire 对于您的第二个建议,您能否给我一些示例代码或如何执行此操作的参考?如果您能提供我的 JSON 的完整代码,我们将非常感激!

标签: json swift multidimensional-array alamofire objectmapper


【解决方案1】:

如果你的 JSON 结构是 Array of arrays,你可以使用:

让 responseArrayOfArrays = Mapper().mapArrayOfArrays(JSONObject: response?.rawValue)

【讨论】:

    猜你喜欢
    • 2016-12-31
    • 2020-09-27
    • 2015-10-25
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 2015-11-27
    相关资源
    最近更新 更多