简体   繁体   中英

Handle JSON response data and String response data respectively in callback

My backend can either return JSON or plain string data in response.

let task = session.dataTask(with: request as URLRequest) { data, response, error in
    if error == nil {
       // Handle response data, but it could be JSON & it could also be String data, how to check and distinguish & handle respectively?
       if let data = data {
                // it fails here if the data is String
                if let jsonDataDict = try? JSONSerialization.jsonObject(with: data) as? JSONDataDict {

                } else {
          }

    }
}

In the response callback, how to check wither the response data is JSON format or String , how to handle respectively?

Try with String initialiser passing data an UTf8 as string encoding

if let data = data {
                // it fails here if the data is String
                if let jsonDataDict = try? JSONSerialization.jsonObject(with: data) as? JSONDataDict {

                } else {
                if let dataString = String(data: data, encoding: .utf8){
                      debugPrint(dataString)
                }
          }

    }
 let jsonDataDict = try? JSONSerialization.jsonObject(with: data) as? JSONDataDict

 if let strJSON = jsonDataDict as? [String:String] //you can cast in string as
 {
    if strJSON?.isEmpty == false {
        //It is empty
    } 

 }
if let data = data {
        if data is Data {
            //do operation with Data
            if let jsonDataDict = try? JSONSerialization.jsonObject(with: data) as? JSONDataDict {
            }
        }
        else if data is String {
            //do operation with string
        }
    }

AppleDoc

Use the type check operator (is) to check whether an instance is of a certain subclass type. The type check operator returns true if the instance is of that subclass type and false if it is not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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