json 动态 key

动态key

优点:数据结构可读性高,运行速度也快。
缺点:前端解析不方便。

{
    "rows": [
        ["Off", {
            "type": "i32_",
            "i32_": -1
        }],
        ["test1", {
            "type": "i32_",
            "i32_": 0
        }],
        ["test2", {
            "type": "i32_",
            "i32_": 1
        }],
        ["test3", {
            "type": "i32_",
            "i32_": 2
        }],
        ["test4", {
            "type": "i32_",
            "i32_": 3
        }]
    ],
    "rowsCount": 5,
    "rowsVersion": 0,
    "roles": {}
}

JSONDecoder

nestedUnkeyedContainer: 存储没秘钥的容器
unkeyedContainer: 存储非键值的编码容器
isAtEnd: 容器中是否还剩余需要解码的元素

Swift

// A类核心代码
var unkeyedContainer = try container.nestedUnkeyedContainer(forKey: .rows)
// 遍历所有元素
while !unkeyedContainer.isAtEnd {
  if let row = try? unkeyedContainer.decode(B.self) {
    self.rows.append(row)
  }
}

// B类核心代码
var container = try decoder.unkeyedContainer()
while !container.isAtEnd {
    // 获取动态 key值
    self.name = try container.decode(String.self)
    self.value = try container.decode(ActiveFilterResponse.self)
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容