我正在尝试使用 ObjectMapper 来使用 JSON 响应。到目前为止,我的回复是这样的:
{
"paramsStructure": [
{
"tiles": {
"0": {
"layout": {
"column": 0,
"colSpan": "1",
"rowSpan": "1",
"row": 0
},
"type": "2"
},
"1": {
"layout": {
"column": 1,
"colSpan": "1",
"rowSpan": "1",
"row": 0
},
"type": "2"
}
},
"title": "...",
"rowCount": "4",
"colCount": "2",
"key": "...",
"icon": "..."
}
]
}
到目前为止,我已经为整个 paramsStructure 和 Single Structure 对象的嵌套集合创建了 StructuresObject。现在我想将图块映射到嵌套在 Structure 对象中的 TileStructure 对象集合中,如下所示。
class SingleStructure : Mappable{
var columns: Int = 0
var title: String = ""
var key: String = ""
var icon: String = ""
var tilesStructure : [Int: TileStructure]?
required init?(map: Map) {
}
func mapping(map: Map) {
title <- map["title"]
key <- map["key"]
icon <- map["icon"]
columns <- (map["colCount"], TransformOf<Int, String>(
fromJSON: {item in return Int(item!)},
toJSON: {_ in return "$0"}))
//need here parsing of tilesStructure
}
}
我主要需要将此 JSON 切片字典映射到 [Int: TileStructure] 中,其中键是字典键,而 TileStructure 是包含“布局”和“类型”属性的可映射对象。
预先感谢您的帮助 :)
编辑!!!
我尝试了 denis_lor 方法,但是当我从 RxAlamofire 运行解析数据时,出现以下异常:
keyNotFound(CodingKeys(stringValue: "tiles", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"tiles\", intValue: nil) (\"tiles\").", underlyingError: nil))
这就是我调用请求的方式
return RxAlamofire.requestData(.get, GlobalSettings.GET_DEVICE_MAIN_STRUCTURE, parameters: parameters, headers: headers)
.debug()
.mapObject(type: ParamsStructure.self)
这就是我的对象映射器:
extension ObservableType {
public func mapObject<T: Codable>(type: T.Type) -> Observable<T> {
return flatMap { data -> Observable<T> in
let responseTuple = data as? (HTTPURLResponse, Data)
guard let jsonData = responseTuple?.1 else {
throw NSError(
domain: "",
code: -1,
userInfo: [NSLocalizedDescriptionKey: "Could not decode object"]
)
}
let decoder = JSONDecoder()
let object = try decoder.decode(T.self, from: jsonData)
return Observable.just(object)
}
}
}
我认为问题可能出在编码上,而这就是造成那些转义“\”的原因,而这些转义则归于键不匹配。