I am trying to user ObjectMapper to consume JSON response. So far my response looks like this:
{
"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": "..."
}
]
}
So far I have created StructuresObject for whole paramsStructure and nested collection of Single Structure object. Now I want to map tiles into TileStructure objects collection nested inside Structure object looking like this.
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
}
}
I mainly I need to map this JSON tiles dictionary into [Int: TileStructure] where key is dictionary key and TileStructure is mappable object containing "layout" and "type" attributes.
Thank you in advance for your help :)
EDIT!!!
I tried denis_lor approach but when I run parsing data from RxAlamofire I get following exception:
keyNotFound(CodingKeys(stringValue: "tiles", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"tiles\", intValue: nil) (\"tiles\").", underlyingError: nil))
This is how I call request
return RxAlamofire.requestData(.get, GlobalSettings.GET_DEVICE_MAIN_STRUCTURE, parameters: parameters, headers: headers)
.debug()
.mapObject(type: ParamsStructure.self)
And thats my object mapper:
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)
}
}
}
I think that the problem is maybe encoding and thats what creates those escape "\" what falls to keys missmatch.