![](/img/trans.png)
[英]When decoding a Codable struct from JSON, how do you initialize a property not present in the JSON?
[英]How do I map a codable JSON struct into Data for decoding a response?
我在编译以下代码时遇到问题 - 它失败并显示“'无法将'CheckUserNameAvailability'类型的值转换为闭包结果类型'JSONDecoder.Input'(又名'Data')”。
我如何 map 服务器返回的CheckUserNameAvailability
JSON 到Data
?
// This is the JSON returned by the server
// {
// "Username" : "Foo1Bar2",
// "Available" : true
// }
struct CheckUserNameAvailability: Codable {
let Username: String
let Available: Bool
}
enum tvAPI {
static func checkUserName(username: String) -> AnyPublisher<CheckUserNameAvailability, Error> {
// ...
}
}
func testUserName() {
var cancellable: AnyCancellable?
let me = "Foo1Bar2"
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .useDefaultKeys
cancellable = tvAPI.checkUserName(username: me)
.map { $0 } // compilation fails with “Cannot convert value of type 'CheckUserNameAvailability' to closure result type 'JSONDecoder.Input' (aka 'Data')”
.decode(type: [CheckUserNameAvailability].self, decoder: JSONDecoder())
// .print()
.sink(receiveCompletion: {completion in
print(completion)
},
receiveValue: { availability in
print("\(availability)")
})
RunLoop.main.run(until: Date(timeIntervalSinceNow: 10))
withExtendedLifetime(cancellable, {})
}
tvAPI.checkUserName(username:)
返回具有 output 类型CheckUserNameAvailability
的发布者。 发布者上的decode
方法要求发布者的 output 与解码器的输入相匹配:
func decode<Item, Coder>(type: Item.Type, decoder: Coder) ->
Publishers.Decode<Self, Item, Coder> where
Item : Decodable,
Coder : TopLevelDecoder,
Self.Output == Coder.Input
但是, CheckUserNameAvailability
与JSONDecoder.Input
(又名Data
)不兼容。
您不需要解码数据:
cancellable = tvAPI.checkUserName(username: me)
// .print()
.sink(receiveCompletion: { completion in
print(completion)
}, receiveValue: { availability in
print("\(availability)")
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.