Reputation: 187
I try to map a string response with object mapper by my result base.
this is result class :
import ObjectMapper
class Result< T : Mappable > : Mappable {
var data: T?
var status: String?
var message: String?
var error: String?
init?(data: T?, status: String?, error: String?){
self.data = data
self.status = status
self.error = error
}
required init?(map: Map){
}
func mapping(map: Map) {
data <- map["data"]
status <- map["status"]
message <- map["message"]
error <- map["error"]
}
}
and also this is my network class:
import Foundation
import ObjectMapper
final class Network<T:Mappable>{
init() {
}
open func requestItem(_ router: BaseRouter, completionHandler: @escaping (Any?, Error?) -> Void) {
APIClient.Instance.requestJSON(router) { (response, error) in
if let error = error {
completionHandler(nil, APIError(code:ErrorCode.NetworkFailed, message:error.localizedDescription))
}
else if let json = response {
var convertedString : String?
do {
let data1 = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
convertedString = String(data: data1, encoding: String.Encoding.utf8)
print(convertedString!.description)
} catch let myJSONError {
print(myJSONError)
}
let result : Result<T>? = Mapper<Result<T>>().map(JSONString: convertedString!)
if let success = result?.status, success == "success" {
completionHandler(result?.data, nil)
}
else {
completionHandler(nil, APIError(code:ErrorCode.HandledInternalError, message:(result?.error)!))
}
}
else {
completionHandler(nil, APIError(code:ErrorCode.EmptyJSONException, message:"Empty JSON Exception"))
}
}
}
}
the response is :
{
"status" : "success",
"data" : "01CPSE6AQXVK554MTGENETKW24"
}
I try to map it but because of String is not a mappable class, I can not do. map["data"] variable should assign only string, not another complex class. Is there anyone can help me about this problem?
Upvotes: 1
Views: 997
Reputation: 187
Finally I can relies that what the wrong is with this code.
extension String : Mappable {
}
That's all.
Upvotes: 1