fselva
fselva

Reputation: 457

Swift: check if jsonObjectWithData is json or not

I have a swift application that communicates by http with a server,

The answers I get by this server may be json, or not. I need to check what they are to print the answer as a Dictionary or as an Array, in order to avoid the fatal error: unexpectedly found nil while unwrapping an Optional value at the NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

This is my 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

What I try to get is something like:

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)
    }

Thank you for your help. Regards.

Upvotes: 1

Views: 2954

Answers (2)

Mushtaque Ahmed
Mushtaque Ahmed

Reputation: 303

I have done something like this for Swift 3.0 and Its working for me.

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
        }

    }

Upvotes: 0

Eric Aya
Eric Aya

Reputation: 70118

You can try the casts in an if let like this:

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")
}

Update for 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)
}

Upvotes: 4

Related Questions