Operator之编码解码(Encoding and decoding)
开发中最常用的场景是对JSON数据进行编码与解码
Encoding
fileprivate struct PostmanEchoTimeStampCheckResponse: Codable {
let valid: Bool
}
let dataProvider = PassthroughSubject<PostmanEchoTimeStampCheckResponse, Never>()
.encode(encoder: JSONEncoder())
.sink { data in
print(".sink() data received \(data)")
let stringRepresentation = String(data: data, encoding: .utf8)
print(stringRepresentation)
})
Decoding
let testUrlString = "https://postman-echo.com/time/valid?timestamp=2016-10-10"
// checks the validity of a timestamp - this one should return {"valid":true}
// matching the data structure returned from https://postman-echo.com/time/valid
fileprivate struct PostmanEchoTimeStampCheckResponse: Decodable, Hashable {
let valid: Bool
}
let remoteDataPublisher = URLSession.shared.dataTaskPublisher(for: URL(string: testUrlString)!)
// the dataTaskPublisher output combination is (data: Data, response: URLResponse)
.map { $0.data }
.decode(type: PostmanEchoTimeStampCheckResponse.self, decoder: JSONDecoder())
JSON编码与解码按固定格式写就成,没有什么难理解的概念