Swift ObjectMapper-将JSON字典映射为嵌套对象
我正在尝试使用ObjectMapper来使用JSON响应。到目前为止,我的回答如下:Swift ObjectMapper-将JSON字典映射为嵌套对象,swift,objectmapper,rxalamofire,Swift,Objectmapper,Rxalamofire,我正在尝试使用ObjectMapper来使用JSON响应。到目前为止,我的回答如下: { "paramsStructure": [ { "tiles": { "0": { "layout": { "column": 0, "colSpan": "1", "rowSpan": "1", "row": 0 },
{
"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和单个结构对象的嵌套集合创建了StructuresObject。现在我想将平铺映射到嵌套在结构对象内的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
}
}
这就是我所谓的请求
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)
}
}
扩展类型{
公共函数映射对象(类型:T.type)->可观察{
返回平面图{data->在
让responseTuple=数据为?(HTTPURLResponse,数据)
让jsonData=responseTuple?1其他{
抛出错误(
域:“”,
代码:-1,
userInfo:[NSLocalizedDescriptionKey:“无法解码对象”]
)
}
let decoder=JSONDecoder()
let object=try decoder.decode(T.self,from:jsonData)
返回可观察。仅(对象)
}
}
}
我认为问题可能在于编码,而这正是造成这些转义“\”的原因,而这些转义属于键不匹配。在json结构中使用动态键的关键是使用
字典,就像我使用[String:Tile]
一样
您可以尝试使用新的:
您可以在此处尝试上面的代码:检查您的方法后,我遇到了另一个问题。我在问题更新中描述了它。你知道我该如何解决这个问题吗?这是正确的吗?或者你会得到另一个吗?我认为u是json的一部分,我只是剪切了一些我放在和“ParamssStructure”相同的lvl上的未解析数据。我发送的json是邮递员收到的。好吧,它说它缺少编码键,我添加了它们。你能重试吗@Maciejgrodzkisady,但仍然是同一个例外。它的任务是搜索“tiles”而不是“tiles”。你是否对RxAlamofire使用了这种编码方法。也许可以用ObjectMapper实现同样的功能,因为他使用RxAlamofire.requestJSON结果,到目前为止效果很好。
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)
}
}
import Foundation
public struct ResultParamsStructure: Codable {
public var paramsStructure: [ParamsStructure] = []
enum CodingKeys: String, CodingKey {
case paramsStructure = "paramsStructure"
}
}
public struct ParamsStructure: Codable {
public var tiles: [String:Tile] = [:]
public var title: String = ""
public var rowCount: String = ""
public var colCount: String = ""
public var key: String = ""
public var icon: String = ""
enum CodingKeys: String, CodingKey {
case tiles = "tiles"
case title = "title"
case rowCount = "rowCount"
case colCount = "colCount"
case key = "key"
case icon = "icon"
}
}
public struct Tile: Codable {
public var layout: Layout?
public var type: String = ""
enum CodingKeys: String, CodingKey {
case layout = "layout"
case type = "type"
}
}
public struct Layout: Codable {
public var column: Int = 0
public var colSpan: String = ""
public var rowSpan: String = ""
public var row: Int = 0
enum CodingKeys: String, CodingKey {
case column = "column"
case colSpan = "colSpan"
case rowSpan = "rowSpan"
case row = "row"
}
}
let jsonString = """
{
"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": "..."
}
]
}
"""
let json = jsonString.data(using: .utf8)!
let resultParamsStructure = try? JSONDecoder().decode(ResultParamsStructure.self, from: json)
print(resultParamsStructure?.paramsStructure[0].tiles.keys)
print(resultParamsStructure?.paramsStructure[0].tiles["1"]?.layout?.colSpan)
//# Optional(Dictionary.Keys(["0", "1"]))
//# Optional("1")