How to use the JSON data tutorial in the Swift language

Source: Internet
Author: User

This is a translation of the article, the original source: http://www.raywenderlich.com/82706/working-with-json-in-swift-tutorial

How to use the JSON data tutorial in the Swift language

JSON (full name: JavaScript Object Notation) is a common method of transmitting data in Web services, and JSON is very popular because it is easy to use and readable.

Here is a snippet of JSON:

[  {" Person": {"name":"Dani"," Age":" -"}},  {" Person": {"name":"Ray"," Age":" -"}}]

Parsing JSON data in Objective-c is fairly straightforward:

NSString *age = json[0[@"Person"] [@ "Age"]; NSLog (@ "Dani ' s age is%@", age);

But in a more modern language, Swift, JSON data is cumbersome to parse because of the optionals data type.

if let item = json[0] {  if let person = item['person'  ] {    if let age = person['age'] {      println (age )    }  }}

In the code above, each parsing from JSON data needs to pass the optional binding check, which makes the code more secure, but also complicates parsing, if the more complex jsons code is resolved to become redundant.

Let's start with an example

Download the example to start the program Project . This app is designed to get top25 apps in the App Store.

There are several files inside.

Topapps.json: Contains files for JSON parsing

Appmodel: Representing the application class

DataManager: Gets the local and remote data classes, using the method in this file to load the JSON data.

Viewcontroller: It's empty now, I'm going to write the code in the door later.

Native parsing methods for JSON data

Add the following code to the Viewdidload () method in the Viewcontroller.swift file:

datamanager.gettopappsdatafromfilewithsuccess {(data), Voidinch  //get the first app with optional binding and Nsjsonserialization class//1var parseerror:nserror?Let parsedobject:anyobject? =nsjsonserialization.jsonobjectwithdata (data, options:NSJSONReadingOptions.AllowFragments, error:&parseerror)//2  ifLet Topapps = Parsedobject as?Nsdictionary {ifLet feed = topapps["Feed"] as?Nsdictionary {ifLet apps = feed["entry"] as?Nsarray {ifLet Firstapp = apps[0] as?Nsdictionary {ifLet Imname = firstapp["Im:name"] as?Nsdictionary {ifLet AppName = imname["label"] as?NSString {//3println ("Optional Binding: \ (appName)")            }          }        }      }    }  }}

Results after the run:

Optional Binding:clash of Clans

Parsing JSON data with Swiftjson third-party framework

First download Swiftjson on GitHub, address:https://github.com/lingoer/SwiftyJSON then download the file and then copy the Swiftjson.swfit in the directory to the project directory.

Replace Viewdidload () content:

Overridefunc viewdidload () {super.viewdidload () datamanager.gettopappsdatafromfilewithsuccess {(data)-Voidinch    //use Swiftyjson to get the first-ranked appLet json=JSON (data:data)ifLet AppName = json["Feed"]["entry"][0]["Im:name"]["label"].string{println ("Swiftyjson: \ (appName)")    }  }}

We note that first JSON () initializes data and transforms it into a JSON object

The advantage of using Swiftjson is that it handles all the checks of the optional data type, and we just need to know the key and index of the JSON data, and the rest can be handed to swiftjson for processing.

In the above code, we also use the string method to get the string value, Swiftjson also has a arrayvalue to get the array.

Operation Result:

Swiftyjson:clash of Clans

Get remote JSON data

Add the following methods in Datamanager.swift:

class Func gettopappsdatafromituneswithsuccess (Success: ((itunesdata:nsdata!)- Void)) {   // 1   Loaddatafromurl (Nsurl (stringin      //2      if Let Urldata = data {        //3        Success (Itunesdata:urldata)      }  })}

Then in Viewcontroller.swfit viewdidload () Add the following method:

Get the first app from itunes and via Swiftyjson

datamanager.gettopappsdatafromituneswithsuccess {(itunesdata), VoidinchLet json=JSON (data:itunesdata)ifLet AppName = json["Feed"]["entry"][0]["Im:name"]["label"].string{println ("nsurlsession: \ (appName)")  }  //More soon ...}

Operation Result:

Wiftyjson:clash of Clansnsurlsession:clash of Clans

Parsing json to array arrays

Add the following after more soon in Viewcontroller://1ifLet Apparray = json["Feed"]["entry"].arrayvalue {//2var apps=[Appmodel] ()//3   forAppdictinchApparray {var appname:string? = appdict["Im:name"]["label"].stringvalue var appurl:string? = appdict["Im:image"][0]["label"].stringvalue var app=Appmodel (Name:appname, Appstoreurl:appurl) apps.append (APP)}//4println (Apps)}

Traverse and save from JSON data into an array of apps of type Appmodel.

To run the program:

In the real program, we will display the data through UITableView or Uicollectionview.

This is the method of parsing JSON data using native classes and third-party class library Swfitjson.

How to use the JSON data tutorial in the Swift language

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.