好吧,像标题这样的家伙说,我有一个响应服务调用JSON数组,我找不到用Combine解码的方法:第一个月
服务响应:https://codebeautify.org/alleditor/y228809f7
我的请求代码:
public func getGasStationDiscounts(requestModel: GasStationDiscountsRequestDomainModel) -> CiMAObservable<GasStationDiscountsDomainModel> {
guard let url = URL(string: RepositoryConstants.baseURL + String(format: RepositoryConstants.EndPoints.gasStationDiscounts, requestModel.gasStationID)) else {
return Fail(error: NSError(domain: "URL Invalid", code: 001, userInfo: nil)).eraseToAnyPublisher()
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "GET"
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
return URLSession.shared.dataTaskPublisher(for: urlRequest)
.map(\.data)
.decode(type: GasStationDiscountsDataModel.self, decoder: JSONDecoder())
.map { model -> GasStationDiscountsDomainModel in
model.parseToDomainModel()
}.eraseToAnyPublisher()
}
可解码文件:https://codebeautify.org/alleditor/y2296aefe
所以继续,我的问题是试图解码它,因为它是一个数组,在我的项目中,我使用不同的层,如数据,域和表示(不要问架构,因为是一个新的,在GitHub上的CiMA),它是一个混合毒蛇拱。
先谢了!
- EDITED:SOLVED!**所以最后我找到了一个解决方案,不破坏我的架构。所以这里的小变化解码文件:https://codebeautify.org/alleditor/y22ad811e
以及请求上的最后更改:
public func getGasStationDiscounts(requestModel: GasStationDiscountsRequestDomainModel) -> CiMAObservable<GasStationDiscountsDomainModel> {
guard let url = URL(string: RepositoryConstants.baseURL + String(format: RepositoryConstants.EndPoints.gasStationDiscounts, requestModel.gasStationID)) else {
return Fail(error: NSError(domain: "URL Invalid", code: 001, userInfo: nil)).eraseToAnyPublisher()
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "GET"
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
return URLSession.shared.dataTaskPublisher(for: urlRequest)
.map(\.data)
.decode(type: [GasStationDiscountsDataModel].self, decoder: JSONDecoder())
.map { model -> GasStationDiscountsDomainModel in
let stationDiscountsDomainModel = model.map { model -> StationDiscountDomainModel in
model.parseToDomainModel()
}
return GasStationDiscountsDomainModel(stationDiscounts: stationDiscountsDomainModel)
}
.mapError { error in
print(error.localizedDescription)
return error
}.eraseToAnyPublisher()
}
2条答案
按热度按时间g6ll5ycj1#
响应似乎是一个数组。没有顶级元素。请用途:
qzwqbdag2#
创建自定义运算符,如下所示:
然后使用它: