![](/img/trans.png)
[英]Can I parse json either into a string or another concrete type as object?
[英]Can you decode a child JSON object into its string representation instead of a concrete type?
好吧,问一个问题类似于这一个,我贴的一天。 这里的区别是我想知道子对象的 json 是否可以作为 JSON 本身的转义字符串读入而不是被解码。
考虑这个json ...
{
"value" : "SomeValue",
"child" : {
"prop1" : "Value1",
"prop2" : "Value2"
}
}
您可以毫无问题地将其解码为这些类...
class Wrapper : Codable {
let value : String
let child : ChildObject
}
class ChildObject : Codable {
let prop1 : String
let prop2 : String
}
我想知道是否有可能编写一个自定义解码器,让我将它解码成这个......
class Wrapper : Codable {
let value : String
let child : String <-- Note: String
}
......并且让 Wrapper.child 等于这个......
// Wrapper.child holds a string containing the escaped, raw JSON
Wrapper.child == "{\"prop1\":\"Value1\",\"prop2\":\"Value2\"}"
到目前为止,我已经找到了唯一的解决办法是明确解码成类似AnyCodable
(GitHub上这里),这是一种荣耀匿名可编码实现,然后重新序列化回JSON其分配给在初始化的实际属性之前。 似乎有点矫枉过正,但确实有效。
public init(from decoder: Decoder) throws {
// Get the container for the CodingKeys
let container = try decoder.container(keyedBy: CodingKeys.self)
// Set 'value' directly as a string
value = try container.decode(String.self, forKey: .value)
// For 'child', Decode to an anonymous codable type,
// Re-serialize that codable type back to JSON data
// Convert that JSON data into a string, using that to set 'child'
// decode an type-erased Codable object
let anyCodable = try container.decode(AnyCodable.self, forKey: .child)
// Reencode it back to JSON
let encoder = JSONEncoder()
let childJsonData = try encoder.encode(anyCodable)
// Set that JSON on the object's string property
child = String(data:childJsonData, encoding:.utf8)!
}
我只是觉得解码很“臭”,只是再次重新编码。 希望有一种方法可以在没有额外步骤的情况下做到这一点。
您正在寻找替代解决方案,下面的这个是替代解决方案。
在 ChildObject 类型上实现 CustomStringConvertible。
class ChildObject : Codable, CustomStringConvertible {
let prop1 : String
let prop2 : String
var description: String {
return "\(prop1) --- \(prop2)"
}
}
然后调用描述getter
child = childJsonData.description
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.