我正在解析需要从服务器上的字典(这是一种遗留数据格式)转换为客户端上的简单字符串数组的响应。因此,我想将名为“data”的键解码为字典,这样我就可以遍历键并在客户端创建一个字符串数组。
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
do {
let some_data_dictionary = try values.decode([String:Any].self, forKey: CodingKeys.data)
for (kind, values) in some_data_dictionary {
self.data_array.append(kind)
}
} catch {
print("we could not get 'data' as [String:Any] in legacy data \(error.localizedDescription)")
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是: Ambiguous reference to member 'decode(_:forKey:)'
在测试新的 Codable 如何与 NSCoding 交互时,我使用包含 Codable 结构的 Class 进行了涉及 NSCoding 的操场测试。丝毫
struct Unward: Codable {
var id: Int
var job: String
}
class Akward: NSObject, NSCoding {
var name: String
var more: Unward
init(name: String, more: Unward) {
self.name = name
self.more = more
}
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(more, forKey: "more")
}
required init?(coder aDecoder: NSCoder) {
name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
more = aDecoder.decodeObject(forKey: "more") as? Unward ?? Unward(id: -1, job: …Run Code Online (Sandbox Code Playgroud) 鉴于这个类:
class MyClass: Codable {
var variable : Codable? = nil
}
Run Code Online (Sandbox Code Playgroud)
我得到错误:
类型“MyClass”不符合协议“Decodable”
类型“MyClass”不符合协议“Encodable”
如何将符合 Codable 的通用变量作为 Codable 类中的属性?
我用于后端调用的服务返回所有这些 json 结构:
{
"status" : "OK",
"payload" : **something**
}
Run Code Online (Sandbox Code Playgroud)
哪里的东西可以是一个简单的字符串:
{
"status" : "OK",
"payload" : "nothing changed"
}
Run Code Online (Sandbox Code Playgroud)
或嵌套的 json(具有任何属性的任何 json),例如:
{
"status" : "OK",
"payload" : {
"someInt" : 2,
"someString" : "hi",
...
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的结构:
struct GenericResponseModel: Codable {
let status:String?
let payload:String?
}
Run Code Online (Sandbox Code Playgroud)
我想始终将“有效负载”解码为字符串。因此,在第二种情况下,我希望“GenericResponseModel”的有效负载属性包含该字段的 json 字符串,但是如果我尝试解码该响应,则会收到错误消息:
Type 'String' mismatch: Expected to decode String but found a dictionary instead
Run Code Online (Sandbox Code Playgroud)
可以存档我想要的吗?
非常感谢
我有以下 Swift 结构
struct Session: Encodable {
let sessionId: String
}
struct Person: Encodable {
let name: String
let age: Int
}
let person = Person(name: "Jan", age: 36)
let session = Session(sessionId: "xyz")
Run Code Online (Sandbox Code Playgroud)
我需要编码为具有以下格式的 json 对象:
{
"name": "Jan",
"age": 36,
"sessionId": "xyz"
}
Run Code Online (Sandbox Code Playgroud)
的所有键Session都合并到Person
我想过使用带有自定义Encodable实现的容器结构,我使用 aSingleValueEncodingContainer但它显然只能编码一个值
struct RequestModel: Encodable {
let session: Session
let person: Person
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(person)
// crash …Run Code Online (Sandbox Code Playgroud) 我正在使用泛型和可编码的URLSession.
当我收到来自 API 的响应时,我检查状态是否在 200 - 299 范围内并像这样解码数据
guard let data = data, let value = try? JSONDecoder().decode(T.self, from: data) else {
return completion(.error("Could not decode JSON response"))
}
completion(.success(value))
Run Code Online (Sandbox Code Playgroud)
然后将其传递给完成处理程序,一切正常。
我有一个新的端点,我也必须 POST,但是,这个端点返回一个没有内容正文的 204。
因此,我无法解码响应,只是因为我无法传入类型?
我的完成处理程序期望
enum Either<T> {
case success(T)
case error(String?)
}
Run Code Online (Sandbox Code Playgroud)
并像这样打开我的响应状态代码
case 204:
let value = String(stringLiteral: "no content")
return completion(.success(value))
Run Code Online (Sandbox Code Playgroud)
产生错误
“Either< > ”中的成员“success”产生“Either”类型的结果,但上下文需要“Either< >”
我的 APIClient 是
protocol APIClientProtocol: class {
var task: URLSessionDataTask { get set }
var session: SessionProtocol …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个通用函数来解析几种不同的数据类型。
最初这个方法只适用于 Codable 类型,所以它的泛型类型被约束,<T: Codable>一切都很好。不过现在,我正在尝试扩展它以检查返回类型是否为 Codable,并根据该检查相应地解析数据
func parse<T>(from data: Data) throws -> T? {
switch T.self {
case is Codable:
// convince the compiler that T is Codable
return try? JSONDecoder().decode(T.self, from: data)
case is [String: Any].Type:
return try JSONSerialization.jsonObject(with: data, options: []) as? T
default:
return nil
}
}
Run Code Online (Sandbox Code Playgroud)
所以,你可以看到类型检查工作正常,但我被困在得到JSONDecoder().decode(:)接受T的Codable类型,一旦我检查了,这是。上面的代码不能编译,有错误
Cannot convert value of type 'T' (generic parameter of instance method 'parse(from:)') to expected argument type 'T' (generic parameter …
我已经在这里看到了许多其他与我类似的问题,但我无法找到我的案例 - 如果我错过了一些明显的问题,我深表歉意!
我有一个“事务”类,其中包含一些属性,所有这些属性都符合 codable 并且可以很好地保存/加载。我刚刚添加了一个字典并收到以下错误:类型“事务”不符合协议“可解码”和“可编码”。
字典是:
var splitTransaction: [String:(amount: Money<GBP>, setByUser: Bool)]? {
Run Code Online (Sandbox Code Playgroud)
Money 来自何处:https : //github.com/Flight-School/Money(Money 已经符合 codable,我还有其他类型为 Money 的属性运行良好。
从https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types我想我必须使用编码密钥来编码/解码 splitTransaction,但这是否意味着我也必须为我的其他每个属性都有一个编码密钥? 然后也提供一种编码/解码它们的方法?或者有没有办法让所有其他属性自动进行编码/解码,而只是为 splitTransaction 提供一种手动工作的方法。
非常感谢任何指导!
我有一个来自 API 的 JSON 响应,但我无法弄清楚如何使用 Swift Codable 将其转换为用户对象(单个用户)。这是 JSON(为了便于阅读,删除了一些元素):
{
"user": [
{
"key": "id",
"value": "093"
},
{
"key": "name",
"value": "DEV"
},
{
"key": "city",
"value": "LG"
},
{
"key": "country",
"value": "IN"
},
{
"key": "group",
"value": "OPRR"
}
]
}
Run Code Online (Sandbox Code Playgroud) 在嵌套Codable结构中使用解码器时,有没有办法访问父结构的属性?
我能想到的唯一方法(尚未测试)是在父结构中也使用手动解码器,在userInfo字典中设置属性,然后userInfo在子结构中访问。但这会导致大量样板代码。我希望有一个更简单的解决方案。
struct Item: Decodable, Identifiable {
let id: String
let title: String
let images: Images
struct Images: Decodable {
struct Image: Decodable, Identifiable {
let id: String
let width: Int
let height: Int
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
width = try container.decode(Int.self, forKey: .width)
height = try container.decode(Int.self, forKey: .height)
// How do I get `parent.parent.id` (`Item#id`) here?
id = "\(parent.parent.id)\(width)\(height)"
}
}
let original: Image
let …Run Code Online (Sandbox Code Playgroud) codable ×10
swift ×10
swift4 ×3
json ×2
casting ×1
decoding ×1
dictionary ×1
generics ×1
identifiable ×1
jsondecoder ×1
nscoding ×1
nsurlsession ×1
struct ×1
type-erasure ×1
urlsession ×1