gpt4 book ai didi

json - Swift/JSONEncoder : Encoding class containing a nested raw JSON object literal

转载 作者:行者123 更新时间:2023-12-04 08:12:07 34 4
gpt4 key购买 nike

我在 Swift 中有一个类,其结构类似于:

class MyClass {
var name: String
var data: String
}
可以在哪里初始化 data包含编码为字符串的 JSON 对象。
var instance = MyClass()
instance.name = "foo"
instance.data = "{\"bar\": \"baz\"}"
我现在想使用 JSONEncoder 序列化这个实例,我会得到类似这样的输出:
{
"name": "foo",
"data": "{\"bar\": \"baz\"}"
}
然而,我真正想要的是
{
"name": "foo",
"data": {
"bar": "baz"
}
}
我可以使用 JSONEncoder 实现这一点吗? (不改变 data 类型而不是 String )

最佳答案

您首先需要解码 data作为通用 JSON。这有点乏味,但不是太难。见 RNJSON对于我写的版本,或者这里是处理您的问题的精简版本。

enum JSON: Codable {
struct Key: CodingKey, Hashable {
let stringValue: String
init(_ string: String) { self.stringValue = string }
init?(stringValue: String) { self.init(stringValue) }
var intValue: Int? { return nil }
init?(intValue: Int) { return nil }
}

case string(String)
case number(Double) // FIXME: Split Int and Double
case object([Key: JSON])
case array([JSON])
case bool(Bool)
case null

init(from decoder: Decoder) throws {
if let string = try? decoder.singleValueContainer().decode(String.self) { self = .string(string) }
else if let number = try? decoder.singleValueContainer().decode(Double.self) { self = .number(number) }
else if let object = try? decoder.container(keyedBy: Key.self) {
var result: [Key: JSON] = [:]
for key in object.allKeys {
result[key] = (try? object.decode(JSON.self, forKey: key)) ?? .null
}
self = .object(result)
}
else if var array = try? decoder.unkeyedContainer() {
var result: [JSON] = []
for _ in 0..<(array.count ?? 0) {
result.append(try array.decode(JSON.self))
}
self = .array(result)
}
else if let bool = try? decoder.singleValueContainer().decode(Bool.self) { self = .bool(bool) }
else if let isNull = try? decoder.singleValueContainer().decodeNil(), isNull { self = .null }
else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [],
debugDescription: "Unknown JSON type")) }
}

func encode(to encoder: Encoder) throws {
switch self {
case .string(let string):
var container = encoder.singleValueContainer()
try container.encode(string)
case .number(let number):
var container = encoder.singleValueContainer()
try container.encode(number)
case .bool(let bool):
var container = encoder.singleValueContainer()
try container.encode(bool)
case .object(let object):
var container = encoder.container(keyedBy: Key.self)
for (key, value) in object {
try container.encode(value, forKey: key)
}
case .array(let array):
var container = encoder.unkeyedContainer()
for value in array {
try container.encode(value)
}
case .null:
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
}
有了它,您可以解码 JSON,然后重新编码它:
extension MyClass: Encodable {
enum CodingKeys: CodingKey {
case name, data
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)

let json = try JSONDecoder().decode(JSON.self, from: Data(data.utf8))
try container.encode(json, forKey: .data)
}
}

关于json - Swift/JSONEncoder : Encoding class containing a nested raw JSON object literal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65901928/

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