Swift:检查jsonObjectWithData是否为json

时间:2015-07-08 08:57:57

标签: arrays json swift dictionary

我有一个快速的应用程序,通过http与服务器进行通信,

这台服务器得到的答案可能是json,也可能不是。我需要检查它们是以Dictionary还是Array来打印答案,以避免fatal error: unexpectedly found nil while unwrapping an Optional value

上的NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

这是我的jsonObjectWithData

var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error:nil)!
elimResponse = response?.description        
elim = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

我试图得到的是:

if dataVal is Json{
    elim = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
    println(elimJson)
    }else{
    elim = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSArray
    println(elim)
    }

感谢您的帮助。问候。

2 个答案:

答案 0 :(得分:4)

您可以像if let一样尝试演员:

if let elim = NSJSONSerialization.JSONObjectWithData(dataVal, options: nil, error: nil) as? NSDictionary {
    println("elim is a dictionary")
    println(elim)
} else if let elim = NSJSONSerialization.JSONObjectWithData(dataVal, options: nil, error: nil) as? NSArray {
    println("elim is an array")
    println(elim)
} else {
    println("dataVal is not valid JSON data")
}

Swift 2.0更新

do {
    if let elim = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSDictionary {
        print("elim is a dictionary")
        print(elim)
    } else if let elim = try NSJSONSerialization.JSONObjectWithData(dataVal, options: []) as? NSArray {
        print("elim is an array")
        print(elim)
    } else {
        print("dataVal is not valid JSON data")
    }
} catch let error as NSError {
    print(error)
}

答案 1 :(得分:0)

我为Swift 3.0做了类似的事情,它为我工作。

func isValidJson(check data:Data) -> Bool
    {
        do{
        if let _ = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
           return true
        } else if let _ = try JSONSerialization.jsonObject(with: data, options: []) as? NSArray {
            return true
        } else {
            return false
        }
        }
        catch let error as NSError {
            print(error)
            return false
        }

    }