简体   繁体   English

解码通用可解码类型

[英]Decoding a generic decodable type

I need to create a generic struct that will hold any decodable type which is returned from the network, so I created something like this:我需要创建一个通用结构来保存从网络返回的任何可解码类型,所以我创建了这样的东西:

struct NetworkResponse<Wrapped: Decodable>: Decodable {
    var result: Wrapped
}

so I can use the decoding method like this:所以我可以使用这样的解码方法:

struct MyModel: Decodable {
  var id: Int
  var name: String
  var details: String
}

func getData<R: Decodable>(url: URL) -> AnyPublisher<R, Error>
    URLSession.shared
   .dataTaskPublisher(for: url)
   .map(\.data)
   .decode(type: NetworkResponse<R>.self, decoder: decoder)
   .map(\.result)
   .eraseToAnyPublisher()

//call site
let url = URL(string: "https://my/Api/Url")!
let models: [MyModel] = getData(url: url)
  .sink {
   //handle value here
}

But, I noticed that some responses from the network contains the result key, and some others do not:但是,我注意到来自网络的一些响应包含result键,而另一些则不包含:

with result:结果:

{
"result": { [ "id": 2, "name": "some name", "details": "some details"] }
}

without result:没有结果:

[ "id": 2, "name": "some name", "details": "some details" ]

this results in the following error from the .map(\\.result) publisher because it can't find the result key in the returned json:这会导致.map(\\.result)发布者出现以下错误,因为它在返回的 json 中找不到result键:

(typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil)))

How can I handle either case in the NetworkResponse struct in order to avoid such error?我如何处理NetworkResponse结构中的任何一种情况以避免此类错误?

The JSON your posted isn't valid, but I'm assuming it's a typo and it's actually:您发布的 JSON 无效,但我假设这是一个错字,实际上是:

{ "id": 2, "name": "some name", "details": "some details" }
// or
{ "result": { "id": 2, "name": "some name", "details": "some details" } }

( { } instead of [ ] ) ( { }而不是[ ] )


Probably the cleanest is with a manual decoder that can fall back to another type, if the first type fails:可能最干净的是使用手动解码器,如果第一种类型失败,可以回退到另一种类型:

struct NetworkResponse<Wrapped> {
    let result: Wrapped
}

extension NetworkResponse: Decodable where Wrapped: Decodable {
    private struct ResultResponse: Decodable {
        let result: Wrapped
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        do {
            let result = try container.decode(ResultResponse.self)
            self.result = result.result
        } catch DecodingError.keyNotFound, DecodingError.typeMismatch {
            self.result = try container.decode(Wrapped.self)
        }
    }
}

Alternatively, you can fall back within Combine.或者,您可以退回到 Combine 中。 I would not have gone with this approach, but for completeness-sake:我不会采用这种方法,但为了完整性:

URLSession.shared
   .dataTaskPublisher(for: url)
   .map(\.data)
   .flatMap { data in
       Just(data)
         .decode(type: NetworkResponse<R>.self, decoder: decoder)
         .map(\.result)
         .catch { _ in
             Just(data)
                .decode(type: R.self, decoder: decoder)
         }
   }
   .eraseToAnyPublisher()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM