// 取出来一个转解析response 的方法, 想办法转成我们想要的 JSON funcmapModel(resp: Response) -> MoyaResult<MyServiceModel> { // 1.过滤状态码 guardlet_=try? resp.filterSuccessfulStatusCodes() else { return .failure(resp.statusCode, "服务器访问失败") } // 下面就是服务器返回的数据的问题了 // 2.解析 json // 转换成 jsonString // Setting the NSJSONWritingPrettyPrinted option will generate JSON with whitespace designed to make the output more readable. // the resulting data is a encoded in UTF-8. // Setting the NSJSONReadingMutableLeaves option will make the parser generate mutable NSString objects.
// 打印 json 字符串 print(jsonString) // 3.json 转 model guardlet base =JSONDeserializer<BaseData<MyServiceModel>>.deserializeFrom(json: jsonString) else { return .failure(-1, "数据无效") } /* 转换数据格式分为两种: 1. 无数据,只是表示成功或者失败状态 2. 有数据,返回 0.model 1.只有状态码,和描述字符串 */ // 1. No model data, only status information if base.errcode ==0 { // valid model data success iflet data = base.data { return .success(data) } return .failure(-1, "数据无效") }else { // return valid data, but data is other status return .failure(base.errcode, base.errmsg) } }