我的后端可以返回JSON或纯字符串数据作为响应。
EVERY_SECOND
在回复回调中,如何检查回复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 {
}
}
}
是data
格式还是JSON
,如何分别处理?
答案 0 :(得分:0)
尝试使用String
初始化程序将UTf8作为字符串编码传递数据
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)
}
}
}
答案 1 :(得分:0)
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
}
}
答案 2 :(得分:0)
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
}
}
使用类型检查运算符(is)检查实例是否属于 某些子类型。如果是,则类型检查运算符返回true instance属于该子类类型,如果不是,则为false。