Swift Codable:使用动态键编码结构

时间:2018-12-11 17:38:04

标签: swift codable encodable

我想要具有以下JSON结构(伪示例):

{
    "Admin" : 
    {
        "name" : "John",
        "age" : "42"
    },
    "Sales" : 
    {
        "name" : "John",
        "age" : "42"
    },
    "CEO" : 
    {
        "name" : "Peter",
        "age" : "52",
        "salary" : "100000"
    },
    "Janitor" : 
    {
        "name" : "Matthew",
        "age" : "22"
    }
}

如您所见,结构是确定的,但结构的名称是动态的。

如何将其转换为Swift Codable结构? 当前尝试:

struct Positions: Codable
{
    var posDicts: [String: Position] = [:]
}

struct Position: Codable
{
    let name: String
    let age: Int
    let salary: Int?
}

但是,这将给出以下内容:

"posDicts" : {
    "Admin" : 
    {
        "name" : "John",
        "age" : "42"
    },
    "Sales" : 
    {
        "name" : "John",
        "age" : "42"
    },
    "CEO" : 
    {
        "name" : "Peter",
        "age" : "52",
        "salary" : "100000"
    },
    "Janitor" : 
    {
        "name" : "Matthew",
        "age" : "22"
    }
}

我不需要JSON中的“ posDicts”。 最好/最简单的解决方案是什么?

P.S .:有关可解码Swift Codable with dynamic keys

的相关问题

2 个答案:

答案 0 :(得分:2)

而不是解码

let result = try JSONDecoder().decode(Positions.self, from: data)

删除Positions结构并解码

let result = try JSONDecoder().decode([String:Position].self, from: data)

要对字典进行编码,应将其声明为

 var positions = [String:Position]()

答案 1 :(得分:0)

Vadian的答案是朝正确方向的良好推动。 解决方案是对字典进行编码,而不是对包含字典的结构进行编码。

由于最初的问题是关于编码的,因此以下是一个完整的解决方案:

var positions: [String: Position] = [:]
let json = try? encoder.encode(positions)