gpt4 book ai didi

json - 使用 Codable 解码带有动态编码 key 的 json?

转载 作者:行者123 更新时间:2023-11-28 10:06:10 26 4
gpt4 key购买 nike

我需要解码的 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"
}

我的 Codable 模型:

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.")
}

但是我遇到了解析错误

parse error: The data couldn’t be read because it is missing.

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

最佳答案

你需要

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

--

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

关于json - 使用 Codable 解码带有动态编码 key 的 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53282380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com