使用Codable使用动态编码密钥解码json?

时间:2018-11-13 13:43:35

标签: json swift decode codable

我需要解码的Json示例。在“文本”键中,我们有[String:String]字典。元素的数量以“计数”为单位。我应该如何正确解码?

{
"name": "LoremIpsum",
"index": "1",
"text": {
    "text_1": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ",
    "text_2": "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ",
    "text_3": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. ",
    "text_4": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
},
"count": "4"
}

我的可编码模型:

class Text: Codable {

private enum CodingKeys: String, CodingKey {
    case name, index, count, text
}

public var name: String?
public var index: Int?
public var count: Int?
public var texts: [String]?

init() {
    name = ""
    index = 0
    count = 0
    texts = []
}

init(name: String,
     index: Int,
     count: Int,
     texts: [String]) {
    self.name = name
    self.index = index
    self.count = count
    self.texts = texts
}

func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    var text = container.nestedContainer(keyedBy: CodingKeys.self, forKey: . text)

}    <---- also why do I need this method? 

required public init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)

    self.name = try container.decode(String.self, forKey: .name)
    self.index = Int(try container.decode(String.self, forKey: .index)) ?? 0
    self.count = Int(try container.decode(String.self, forKey: .count)) ?? 0
    let text = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .text)

    for i in (1...self.count!) {
        self.texts!.append(try text.decode(String.self, forKey: Text.CodingKeys.init(rawValue: "text_\(i)") ?? .text))
    }
}

}

然后我用

对其进行解码
if let path = Bundle.main.path(forResource: "en_translation_001", ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
            let jsonObj = try JSONDecoder().decode(Text.self, from: data)
            print("jsonData:\(jsonObj)")
        } catch let error {
            print("parse error: \(error.localizedDescription)")
        }
    } else {
        print("Invalid filename/path.")
    }

但是我遇到了解析错误

  

解析错误:由于缺少数据,因此无法读取数据。

我的代码有什么问题?这是解码这种动态编码密钥的好方法吗?

3 个答案:

答案 0 :(得分:2)

修复JSON

我想您希望索引和计数为数字。因此,请替换此"index": "1"和此"count": "4" 有了这个"index": 1和这个"count": 4

类结构

使用Codable协议,这些CodingKey和编码功能中的任何一个都不是必需的。还将文本属性数据格式更改为[String:String]

因此,像这样替换您的班级:

class Text: Codable {

    public var name: String
    public var index: Int
    public var count: Int
    public var texts: [String: String]

    init(name: String, index: Int, count: Int, texts: [String: String]) {
        self.name = name
        self.index = index
        self.count = count
        self.texts = texts
    }

}

解码

对于解码json,请使用上面编写的内容,

let object = try JSONDecoder().decode(Text.self, from: data)

答案 1 :(得分:1)

您需要

struct Root: Codable {
    let name, index,count: String
    let text: [String:String]
}

-

let res = try? JSONDecoder().decode(Root.self,from:jsonData)

答案 2 :(得分:1)

您需要的最重要的是:

let text = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .text)
texts = try text.allKeys.map { try text.decode(String.self, forKey: $0) }

这会将字典转换为值数组。原则上不对JSON值进行排序,而对allKeys进行排序(因为它是序列化的协议)。

如果仅遵循Decodable而不是Codable,则无需使用encode方法。另外,您的大多数可选项目并不是真正的可选项目。

将这些东西放在一起,您将拥有:

class Text: Decodable {

    private enum CodingKeys: String, CodingKey {
        case name, index, count, text
    }

    public var name: String
    public var index: Int
    public var count: Int
    public var texts: [String]

    init(name: String = "",
         index: Int = 0,
         count: Int = 0,
         texts: [String] = []) {
        self.name = name
        self.index = index
        self.count = count
        self.texts = texts
    }

    required public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        self.name = try container.decode(String.self, forKey: .name)
        self.index = Int(try container.decode(String.self, forKey: .index)) ?? 0
        self.count = Int(try container.decode(String.self, forKey: .count)) ?? 0
        let text = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .text)
        texts = try text.allKeys.map { try text.decode(String.self, forKey: $0) }
    }

}

let jsonObj = try JSONDecoder().decode(Text.self, from: data)