JSON Serialization in Swift iOS - ios

How can I serialize JSON in swift? I am trying to serialize using this method, however it is causing EXC_BAD_INSTRUCTION. For downloading JSON data, I am using NSURLConnection.
var sJson : NSDictionary = NSJSONSerialization.JSONObjectWithData(nsMutData, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
How can I solve it?
Regards

Your root-level data is an array of dictionaries -- not a dictionary; therefore replace your line with:
var sJson = NSJSONSerialization.JSONObjectWithData(nsMutData, options: .MutableContainers, error: nil) as NSArray
I tested it and it now works with your data.
Here's how I tested it after having created a "json.txt" file in my project:
var filePath = NSBundle.mainBundle().pathForResource("json", ofType:"txt")
var nsMutData = NSData(contentsOfFile:filePath)
var sJson = NSJSONSerialization.JSONObjectWithData(nsMutData, options: .MutableContainers, error: nil) as NSArray

This is the swift 2.0 way
let path : String = NSBundle.mainBundle().pathForResource("jsonDict", ofType: "JSON")!;
let data : NSData = NSData(contentsOfFile: path)!;
var jsonDictionary : NSDictionary
do {
jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as! NSDictionary
} catch {
print(error)
}

In Swift 4+, JSON Serialization is best done by utilizing the Decodable and Encodable protocols.
Apple docs about encoding/decoding (or serializing/deserializing)
custom types
Download sample code from Apple on this page
There is also a detailed tutorial by Ray Wenderlich: Encoding and Decoding in Swift

Related

issue retrieve json data in swift iOS

I have issue that I can't retrieving json data in swift, I kept getting error message
var url = NSURL(string: getDataURL)!
var data = NSData(contentsOf: url as URL)
do {
jsonArray = try JSONSerialization.jsonObject(withData: data, options: .allowFragments)!
}
catch let error {
}
I was working with Objective C but I want to switch to Swift language
Folks, please use the code completion feature to find the proper syntax
When you type JSONSerialization. you will see
The appropriate method is
JSONSerialization.jsonObject(with:data, options: .allowFragments)
Or press ⇧⌘0 (zero not O) and look up the method in the documentation by typing or pasting the class. Every developer must be able to read the documentation.
Aside from that you have to cast the result of the deserialization to the expected type
jsonArray = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [[String:Any]]
Try this code send request and get data.
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(fooData!, options: []) as? NSDictionary
{
print(jsonResult)
}else{
return failure(NSError)
}

How do I convert swift Dictionary to NSDictionary

I'm trying to convert a [String : String] (a Swift Dictionary) to NSDictionary, for later use on a JSON library that produces a string
var parcelDict = ["trackingNumber" : parcel.number,
"dstCountry" : parcel.countryCode];
if (parcel.postalService != nil)
{
parcelDict["postalService"] = parcel.postalService;
}
var errorPtr: NSErrorPointer
let dict: NSDictionary = parcelDict
var data = NSJSONSerialization.dataWithJSONObject(dict, options:0, error: errorPtr) as NSData
return NSString(data: data, encoding: NSUTF8StringEncoding)
but let dict: NSDictionary = parcelDict does not work
let dict: NSDictionary = parcelDict as NSDictionary
var data = NSJSONSerialization.dataWithJSONObject(parcelDict as NSMutableDictionary, options:0, error: errorPtr) as NSData
All of these examples do not work. They produce the following errors:
What's the correct way of doing it?
Update:
Code that works
var parcelDict = ["trackingNumber" : parcel.number!,
"dstCountry" : parcel.countryCode!];
if (parcel.postalService != nil) {
parcelDict["postalService"] = parcel.postalService;
}
var jsonError : NSError?
let dict = parcelDict as NSDictionary
var data = NSJSONSerialization.dataWithJSONObject(dict, options:nil, error: &jsonError)
return NSString(data: data!, encoding: NSUTF8StringEncoding)!
You have to cast it like this:
let dict = parcelDict as NSDictionary
Otherwise the Swift Dictionary and NSDictionary are treated almost the same way when using it in methods for ex:
func test(dict: NSDictionary) {}
let dict = ["Test":1]
test(dict)
Will work completely fine.
After your update
If you change your Dictionary value type to non optional String then your error will go away.
[String:String?] change to -> [String:String]
You can use this easy method
let dictSwift = ["key1": "value1", "key1": value2]
let dictNSMutable = NSMutableDictionary(dictionary: dictSwift)
Enjoy coding!
Don't don't need to convert it to an NSDictionary. Just use:
var data = NSJSONSerialization.dataWithJSONObject(parcelDict, options:0, error: errorPtr) as NSData
It's mentioned in this post: Making a JSON object in Swift
Edit
From your screenshots I believe your problem lies in the value type in your parcelDict Dictionary. I can recreate the error with the following code:
let dict = [String: String?]()
let nsDict = dict as NSDictionary // [String: String?] is not convertible to NSDictionary
However, using a String instead of a String? as the value type removes the error.
Therefore, when populating parcelDict perhaps you should only add to it values which are not nil.

Swift parsing json doesn't work

I want to parse a json file, this is in my json file:
{
"currentPowerByClient": 0, <- i want to read this
"currentPowerToClient":518,
"tariff":1,
"totalGasDelivered":1061.004,
"totalPowerByClientHigh":10.704,
"totalPowerByClientLow":23.042,
"totalPowerToClientHigh":912.221,
"totalPowerToClientLow": 693.499
}
this is my swift code, the object called JSONResult contains my JSON code
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:
NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
if let item = jsonResult as NSDictionary? {
if let currentPowerByClient = item["currentPowerByClient"] as? NSDictionary {
println(currentPowerByClient)
}
}
when i run it, it doesn't print anything
The line
if let currentPowerByClient = item["currentPowerByClient"] as? NSDictionary
should be
if let currentPowerByClient = item["currentPowerByClient"] as? NSNumber
because item["currentPowerByClient"] is expected to be a number, not a dictionary. it works then

Parse Google Calendar JSON in SWIFT

I'm brand new to Swift development. I'm trying to build a basic app which will read a feed from Google Calendar which is returned in JSON.
I am able to use a NSURLConnection.sendAsynchronousRequest call as described in this thread: Make REST API call in Swift and I get a result of some sorts.
My problem is I am unable to parse the JSON into some meaningful objects from which I can create a list of upcoming events.
My code this far is:
var url : String = "some url"
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
if (jsonResult != nil){
// No idea how to parse this object as it seems to be a NSDictionary but battling to interact with it.
}
else
{
}
})
Any help would be greatly appreciated.
If you put a breakpoint after
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
then you'll be able to see the dictionary key/value pairs. I copied/pasted your code and see this:
You can access the values by using jsonResult.objectForKey("keyName"). I'm also going to downcast using as DataType.
Example)
let encoding = jsonResult.objectForKey("encoding") as String
let version = jsonResult.objectForKey("version") as String
let feed = jsonResult.objectForKey("feed") as NSDictionary

Nested JSON data will cause crash using NS Dictionary (in Swift)

I'm trying to fetch movie information in JSON format using JSONSerialization in Swift and save it as an NSDictionary. However, calling the Rotten Tomatoes API (in which information is nested) will cause my Playground to crash (without giving me any useful errors).
I know the code is somewhat valid, since calling other APIs which don't nest their data works (but don't fulfill my need).
Here's the code:
func getJSON(urlToRequest: String) -> NSDictionary {
var url = NSURL(string: urlToRequest)
var error: NSError?
let jsonData: NSData = NSData.dataWithContentsOfURL(url , options: NSDataReadingOptions.DataReadingMapped, error: nil)
let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
return jsonDict
}
let movieData: NSDictionary = getJSON(apiURL)
here's a sample from the Rotten Tomatoes API JSON (shortened for illustration purposes, this is the actual JSON file, not the output from my code)
{
"id": 770672122,
"title": "Toy Story 3",
"year": 2010,
"genres": ["Animation", "Kids & Family", "Science Fiction & Fantasy", "Comedy"],
"release_dates": {
"theater": "2010-06-18",
"dvd": "2010-11-02"
},
"ratings": {
"critics_rating": "Certified Fresh",
"critics_score": 99,
"audience_rating": "Upright",
"audience_score": 89
}
}
This code works for me in a Swift iOS app (crashes Xcode when run in a playground:
func getJSON(urlToRequest: String) -> NSDictionary {
var url = NSURL(string: urlToRequest)
var error: NSError?
let jsonData: NSData = NSData.dataWithContentsOfURL(url , options: NSDataReadingOptions.DataReadingMapped, error: nil)
let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
return jsonDict
}
let apiURL = "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122.json?apikey=9p4xwzpgt8xp2vahnyx2sc6g"
let movieData: NSDictionary = getJSON(apiURL)
println(movieData)
It looks like the crash you are getting is a playground error.
Note, Swift is basically guaranteed to have bugs, it is an early Beta.
Also explicitly state they the JSON is example code, not fro running your code.

Resources