反序列化双数组

时间:2019-05-15 17:38:05

标签: json swift

我尝试使用可编码协议在Swift 4.2上反序列化一些JSON。 我的杰森

{  
   "status":1,
   "data":[  
      [  
         {  
            "id":"4klJeiCKTs",
            "body":"first",
            "da":"1442236233",
            "dm":"1442236233"
         },
         {  
            ...
         }
      ]
   ]
}

我的结构和代码:

struct GetEntriesRequest: Decodable{
    var status: Int
    var data: [NestedArrayGetEntries]
}

struct NestedArrayGetEntries: Decodable{
    var elements: [GetEntriesDataFromSession]
}
struct GetEntriesDataFromSession: Decodable{
    var id: String
    var body: String
    var da: String
    var dm: String
}
...
let decoder = JSONDecoder()

            decoder.keyDecodingStrategy = .convertFromSnakeCase
            do {
                let root = try decoder.decode(GetEntriesRequest.self, from: data)
                dataSession = root
            } catch { print(error) }

另外,我尝试了这个结构

var data: [[GetEntriesDataFromSession]]

,但没有成功。在此先感谢

1 个答案:

答案 0 :(得分:0)

data键是一个嵌套数组,没有elements

 var data: [NestedArrayGetEntries]

使用

var data: [[NestedArrayGetEntries]]

struct GetEntriesRequest: Codable {
    let status: Int
    let data: [[NestedArrayGetEntries]]
}

struct NestedArrayGetEntries: Codable {
    let id, body, da, dm: String
}

您在这里也不需要蛇皮箱

  do {
      let root = try JSONDecoder().decode(GetEntriesRequest.self, from: data)
      dataSession = root
   } catch { 
      print(error)
   }