美文网首页
json 动态 key

json 动态 key

作者: 小猪圣骑士 | 来源:发表于2020-12-25 14:48 被阅读0次

动态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)
}

相关文章

网友评论

      本文标题:json 动态 key

      本文链接:https://www.haomeiwen.com/subject/hgybnktx.html