Submit your appAboutContact

How to parse and extract json data in swift

In this new swift 2 tutorial you'll learn how to parse json data structure in order to send complex data structure as a String to an external server. You'll see how to prepare the array of objects to send and how to do the data parsing into the json format. In the second part of this tutorial, you'll see how to extract the json data by using the NSDictionary and NSArray data type.

 Configure the project

Open Swift and create a new iOS single view app. In this example the http protocol is used in order to send and receive the data from this protocol, in swift 2 you'll need to enable it. Search for the info.plist file, right click on it, choose open as - source code and add the following lines.

<key>NSAppTransportSecurity</key>

<dict>

	<key>NSAllowsArbitraryLoads</key>

	<true/>

</dict>

 

Json parsing: let's parse and send the json data to an external server

You'll see now how to parse a data structure and send it as a json String to an external server. In this example we'll send an object with the following structure: request - [string name of the request] ; some_extra_data - [string with the extra data]

 Once the data is parsed as a json element, you'll able to send it as a string to the server. In this example I've prepared a simple server side script that get the posted data and just reply it out. Let's open the ViewController.swift file and define the send_and_parse_json function.

  func send_and_parse_json()
    {
        var send_data:[String:String] = [String:String]()
        
        send_data["request"] = "kaleidosblog"
        send_data["some_extra_data"] = "1"
        
        do
        {
            let json = try NSJSONSerialization.dataWithJSONObject(send_data, options: NSJSONWritingOptions(rawValue: 0))
            let data_string = NSString(data: json, encoding:NSUTF8StringEncoding)
            
            data_request(data_string!)
            
        }
        catch
        {
            
        }
  

    }
    

Using the NSJSONSerialization swift function, you'll able to convert your data structure into the json data format. Now you'll able to send it to your server. Let's implement the data_request function, that will send the json object to your server.

   func data_request(data:NSString)
    {
        
        let url_to_request = "http://www.kaleidosblog.com/tutorial/get_data.php"
        
        let url:NSURL = NSURL(string: url_to_request)!
        let session = NSURLSession.sharedSession()
        
        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
        request.timeoutInterval = 10
        
        let paramString = "data=" + (data as String)
        request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
        
        let task = session.dataTaskWithRequest(request) {
            (
            let data, let response, let error) in
            
            guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
                print("error")
                return
            }
            
            let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            
            print(dataString)
            
        }
        
        task.resume()
        
    }

We'll send a post request and the json data string are defined inside the data post variable. The echo from the server is then printed using the print swift function.

 

Json extraction: let's extract json data sent from a server using the NSDictionary and NSArray

In this second section of the tutorial you'll see how to receive json data structure and how to extract it inside a swift array. In this example you'll see the following data structure:

object [colorsArray]
     Array []
           object[colorName]
           object[hexValue]

Let's first asynchronously download the data from the server using the NSURLSession swift function.

 func get_json_data()
    {
        
        let url_to_request = "http://www.kaleidosblog.com/tutorial/colors.json"
        
        let url:NSURL = NSURL(string: url_to_request)!
        let session = NSURLSession.sharedSession()
        
        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "GET"
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
        request.timeoutInterval = 10
        
        
        let task = session.dataTaskWithRequest(request) {
            (
            let data, let response, let error) in
            
            guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
                print("error")
                return
            }
            
            self.extract_json_data(data!)
            
        }
        
        task.resume()

    }

The guard function has been used to check the right data format. As soon as the data is received, the extract_json_data function is called.

  func extract_json_data(data:NSData)
    {
        var json: AnyObject?

        
        do
        {
            json = try NSJSONSerialization.JSONObjectWithData(data, options: [])
        }
        catch
        {
            return
        }
        
        
        guard let data_dictionary = json as? NSDictionary else
        {
            return
        }
        
        
        guard let data_array = data_dictionary["colorsArray"] as? NSArray else
        {
            return
        }
        
        
        for(var i = 0; i < data_array.count; i++)
        {
            colors.append(Color(data: data_array[i] as! NSDictionary))
        }
        
        
        print(colors)

    }
    

By following the data structure, we'll need to ensure that the data structure follows the right data formats:

object [colorsArray] [NSDictionary]
     Array [] [NSArray]
           object[colorName] [NSDictionary]
           object[hexValue] [NSDictionary]

Let's define now the colors data structure.

    var colors:[Color] = [Color]()
    
    struct Color
    {
        var name:String = ""
        var hex:String = ""
        
        init(data:NSDictionary)
        {
            
            if let add = data["colorName"] as? String
            {
                self.name = add
            }
            
            if let add = data["hexValue"] as? String
            {
                self.hex = add
            }
            
        }
    }
    

Download the complete example for swift 2 from here.

 

Leave a comment








Comments


- 06 July 2016 at 07:57
Hi.... This was very helps to me.. thankz lot... keep it up.. please can you provide any swift related books aur videos on your site?
Andrea - 01 September 2016 at 09:44
Hi, thank you for your comment. Sure I will post some video tutorial about swift! Great advice!
- 02 July 2016 at 10:55
Please ignore my request for the php code - I found it in your comments. I needed to change the if(isset($_POST to if(isset($_REQUEST["data"]))["data"])) for it to work for me. Thanks again!
- 30 June 2016 at 10:18
Is it possible to give the php script to de-encode the json data?
- 01 April 2016 at 14:19
Thanks for the helpful and effective tutorials...
- 02 March 2016 at 03:24
So helpful! But, one issue using the Json Extraction code in a SplitViewController. In the "self.extract_json_data(data!)" line, I get the error "Value of type 'MasterViewController' has no member 'extract_json_data' " Any thoughts on this issue? Thanks in advance!!
Andrea - 03 March 2016 at 20:39
Hi, thank you for your comment. I should see the code. Be sure that you've defined the extract json data function inside the MasterViewController class. If you've defined the function outside, globally, you should remove the self prefix.
- 19 February 2016 at 20:00
Hi! thnx for the code. How can i add a image to the JSON file? I've created a project based on the FoodTracker tutorial provided by apple. I've modified the code to upload the data to a MYSQL server but i can't seem to figure out how to add a image to the upload. do you have any tips?
Andrea - 19 February 2016 at 20:30
Hi, thank you for your comment. You have two ways. One way is to nsert the images directly in base64 format inside the json string, but this option is a bit slow, because it will download everything, and not just the required images that the list has to display at a given time. The best solution is to have inside your mysql table the name/link of the image. You'll send the json data with just the link of the image. Then, you'll have to download the images in async, when needed. Here an example http://www.kaleidosblog.com/uicollectionview-image-gallery-download-and-display-images-inside-the-cell
Joo - 19 February 2016 at 20:48
Hi, Thnx for the quick reply. I have used the example you've given to download and display the images. The only thing that I can't get to work is the upload itself. do you have any examples of image uploads using swift 2?
Andrea - 19 February 2016 at 20:53
I'll write something about this in the next days! I'll send you a note when it's online.
joo - 19 February 2016 at 20:56
Thnx in advance!
- 16 February 2016 at 06:04
will you please give me the php code
Andrea - 16 February 2016 at 10:12
Sure, here it is http://www.kaleidosblog.com/tutorial/get_data.txt





Submit your appAboutContactPrivacy