Swift & JSON Data

Source: Internet
Author: User


Swift and JSON data


We all usually in the development of the APP, believe that the most contact is the JSON data. As long as your App has the ability to read network data, you will inevitably have to deal with JSON. For example, you make a news App, you want to read and parse the news data so that it can be displayed to the user.



So let's take a look at JSON and its application in the app today.



In the first two sections we'll look at the JSON data format, and if you already know more about JSON, you can skip the first two sections and continue reading the following.


What is JSON


First of all, the full name of JSON is called JavaScript object Notation , which translates into Chinese is the JavaScript objects notation , and is a lightweight form of data interaction.



JSON data is divided into three forms, objects, arrays, values.



An object is an unordered collection of "name/value pairs". An object starts with "{" (opening parenthesis) and "}" (the closing parenthesis) ends. Each "name" is followed by a ":" (colon); "' Name/value ' pair ' is separated by", "(comma).






An array is an ordered collection of values (value). An array begins with "[" (the left square bracket), and "]" (the right square bracket) ends. Use "," (comma) to separate values.






The value (value) can be a string enclosed in double quotation marks (string), a numeric value (number), True, false, NULL, an object, or an array. These structures can be nested.






The following is a simple example:


{
  "firstname": "San",
  "lastname" : "Zhang",
  "age": 21,
  "friends": ["Mark","Li"]
}


The above data example, represents a structure, first of all our data is surrounded by a pair of curly braces, then our data is the object type, then it has four properties,,,firstnamelastnameagefriends. Of the first two propertiesfirstnameandlastnamestring types, their values are theSanandZhang. Theageproperty represents age, so it's the value of aNumbertype21.



Note the字符串数字difference between type and type, the value of the string type is enclosed in double quotation marks, and the numeric type does not require double quotes.



Finally,friendsthe value of the property is an array, surrounded by a pair of brackets, and the elements in the array are still string types.



The above is a basic structure of JSON, about JSON more detailed introduction, you can see json.org


JSON Data Instance


After we've seen the JSON format, let's look at how the JSON data is formatted.



Like this weather data interface: HTTP://API.OPENWEATHERMAP.ORG/DATA/2.5/WEATHER?Q=CHINA,BJ&LANG=ZH_CN



If we open this address in a browser, we can see data like this:


{
  "coord": {
    "lon": 116.4,
    "lat": 39.91
  },
  "weather": [
    {
      "id": 520,
      "main": "Rain",
      "description": "rain",
      "icon": "09d"
    },
    {
      "id": 701,
      "main": "Mist",
      "description": "fog",
      "icon": "50d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 300.39,
    "pressure": 1008,
    "humidity": 94,
    "temp_min": 297.15,
    "temp_max": 303.71
  },
  "visibility": 2300,
  "wind": {
    "speed": 1,
    "deg": 140
  },
  "clouds": {
    "all": 75
  },
  "dt": 1437281131,
  "sys": {
    "type": 1,
    "id": 7405,
    "message": 0.0136,
    "country": "CN",
    "sunrise": 1437253268,
    "sunset": 1437305986
  },
  "id": 1816670,
  "name": "Beijing",
  "cod": 200
}


Let's take a quick look at the whole data using a pair of curly braces, that is, the data returned to us, is a JSON object immediately thereafter, the object contains thecoordproperty, the value of this property is an object, there are two properties ' lon ' and ' lat ' Represents a geographic location, followed by a number of other properties that represent weather data.



JSON data format, can be very structured to represent the weather information. and the data structure at a glance, very clear. And there are many online tools to help you better edit and view JSON data.
Like http://www.jsoneditoronline.org.


Working with JSON data in Swift


Once we've learned the JSON data, we'll continue with our topic.





Using Nsjsonserialization


JSONThere are many ways in which data is processed in Swift. First, since Swift can refer to the Cocoa native library, we can use CocoaNSJSONSerializationto manipulate theJSONdata, and this class is well understood, and it transforms theJSONdata into CocoaNSDictionaryNSArray. Let's take a look at howNSJSONSerializationto handle it:


let APIURL = "http://api.openweathermap.org/data/2.5/weather?q=China,bj&lang=zh_cn"

if let url = NSURL (string: APIURL) {

     if let jsonData = NSData (contentsOfURL: url) {

         if let jsonObj: NSDictionary = NSJSONSerialization.JSONObjectWithData (jsonData, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary {

             if let weathers: NSArray = jsonObj ["weather"] as? NSArray {

                 var weatherSummary = "Beijing weather conditions:"

                 for weather in weathers {

                     if let desc: String = weather ["description"] as? String {

                       weatherSummary + = desc + ""

                     }

                 }

                 print (weatherSummary)

             }

         }

     }

} 


Let's explain it one by one.


    1. First, we pass  Let url = Nsurl (string:apiurl)  The weather interface is packaged as Nsurl.
    2. then we use  let jsondata = NSData (contentsofurl:url)  Download the contents of this URL and store it in  NSDatain  .
    3. Next, we'll use  nsjsonserialization  Parse the data into  JSON .
      Let jsonobj:nsdictionary = Nsjsonserialization.jsonobjectwithdata (jsondata, Options: Nsjsonreadingoptions.allzeros, Error:nil) as? Nsdictionary
      Here we  jsonobjectwithdata  method will pass in  nsdata  The data is parsed into JSON objects, and if our   theJSON  root node is stored as an object, then we get a  nsdictionary. And if it is stored as an array, then we get a  nsarray . There are two parameters in the back  options  for JSON read options, as we'll talk about later,error  parameters represent errors in JSON reads, if incoming  Nil  indicates that an error message is not accepted.

    4. After we get the parsed JSON, we can get the information in the same way as the normal collection object:

if let weathers: NSArray = jsonObj ["weather"] as? NSArray {

     var weatherSummary = "Beijing weather conditions:"

     for weather in weathers {

         if let desc: String = weather ["description"] as? String {

           weatherSummary + = desc + ""

         }

     }

     print (weatherSummary)

} 


We'll read the weather here and print it to the screen, for example, on the data above, and print it to the screen like this:


Beijing weather conditions: Shower mist

Read options for Nsjsonserialization


Just now, we usedNSJSONSerializationto parse the JSON data successfully, think it is very cool to use. In retrospect, we have just noticed that there is oneoptionsparameter we did not detail. This we can call it the Read option, the type of this parameter isNSJSONReadingOptions, it can be the following values:


    1. MutableContainers: Lets you change the array and dictionary in the JSON data that is returned.
    2. AllowFragments: Allows data returned by JSON to have multiple root nodes.
    3. MutableLeaves: The string returned by JSON is editable.


I believe some of bold but cautious's friends will find ...






I don't understand what this is all about.



So.. Sir, listen to my one by one.


    • Mutablecontainers


First,MutableContainersThis option lets you change the JSON collection that is returned, so let's take a look at one example:


var jsonString: NSString = "{\" names \ ": [\" James \ ", \" Jobs \ ", \" Tom \ "]}" as NSString
let jsonData = jsonString.dataUsingEncoding (NSUTF8StringEncoding)

if let jsonObj: NSDictionary = NSJSONSerialization.JSONObjectWithData (jsonData !, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary {

     // Before operation
     print (jsonObj) // James, Jobs, Tom

     if let nameArray: NSMutableArray = jsonObj ["names"] as? NSMutableArray {

         nameArray.addObject ("Cook")

     }

     // After the operation
     print (jsonObj) // James, Jobs, Tom, Cook

} 


Let's take a look at the code above, weJSONObjectWithDataadd the read parameter when the method is called, soNSJSONReadingOptions.MutableContainerswe can change our result set, and we notice the code above:


 
if let nameArray:NSMutableArray = jsonObj["names"] as? NSMutableArray {

       nameArray.addObject("Cook")

}


Get thenamesarray and add a new item inside it. Then we print thejsonObjobject again, and the result of this show is that we changed it.



If we remove theJSONObjectWithDataoption when we call the methodNSJSONReadingOptions.MutableContainers, we cannot change the elements of any of these arrays.



The first optionMutableContainerswe've finished. We continue to


    • Allowfragments


Another option parameter is that theAllowFragmentsofficial interpretation of this parameter is to allow the root level of the parsed JSON data, not arrays and objects.



Amount: That sounds weird, isn't it?



This option is really easy to cause ambiguity, including his nameAllowFragments, translated into Chinese called allow fragments , what is allowed to fragment it, I have to practice the study of this before I have always thought so ...






AllowFragmentsMeaning, is it possible to parse such JSON?


{"name":"Jobs"},{"name":"Ive"}


That's what I thought in my mind for some time. Unfortunately, this is not the case at all, if you pass this JSON data to theJSONObjectWithDatamethod, you will get a ruthless parsing error ...



So, what the hell is this thing for?



In fact, the official document is clearly said, you can let the node is not an object or an array. There are only three types in JSON, objects, arrays, values.



In fact, this is the case, allowing your JSON data to be a literal value, such as strings, numbers, and so on.



For example, we can pass in an original string


"something wrong about api"


This data, if you openAllowFragments, is fully parsed (note the double quotes on both sides, which is also included in the returned data). And if you do not turn this option on, the parsing of this data will fail.


 
 
var jsonFragmentString = "\"something wrong about api\"" as NSString

let jsonFragmentData = jsonFragmentString.dataUsingEncoding(NSUTF8StringEncoding)

if let jsonObj: AnyObject = NSJSONSerialization.JSONObjectWithData(jsonFragmentData!, options: .AllowFragments, error: nil) {

// Use the AllowFragments option, and the parsing is successful.
    print(jsonObj)

}


After reading the above code, I believe that everyone instantly understand, the original this guy is doing this use.


    • * * mutableleaves * *
      MutableLeavesoption, this option has kept me from thinking about it, and the document says that with this option, the string attributes of all the leaf nodes of the object will becomeNSMutableString, and I have tried multiple documents and not verified that the resulting string is stillNSStringnotNSMutableString.
Using Nsjsonserialization to create JSON data


Just now we learned how toNSJSONSerializationparse the data. Again, we can use itNSJSONSerializationto build JSON data.



Let's take a look at the following code:


 
 
let names = ["Jobs","Cook","Ive"]

if let jsonData = NSJSONSerialization.dataWithJSONObject(names, options: NSJSONWritingOptions.allZeros, error: nil) {
    let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)
    // ["Jobs","Cook","Ive"]
}


We usedataWithJSONObjectmethods to convert JSON objects into JSON data, and the objects we pass in can be arrays or dictionaries, which correspond to arrays and objects in JSON, respectively.



We note thatdataWithJSONObjectthis method also has anoptionsoption to control the options for building the JSON, typeNSJSONWritingOptions. It has only one option, that isNSJSONWritingOptions.PrettyPrinted.



The function of this option is also self-evident, that is, to make the generated JSON data is well formatted:


 
let jsonObj = ["name":"Jobs","friends":["Ive","Cook"]]

if let jsonData = NSJSONSerialization.dataWithJSONObject(jsonObj, options: NSJSONWritingOptions.PrettyPrinted, error: nil) {

    let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)

}


Using thePrettyPrintedoptions, our output of JSON is such a well-formatted:


{  "name": "Jobs",  "friends": [ "Ive", "Cook" ]}


If we don't use this option, then the output we get is this:


{"name": "Jobs","friends": ["Ive","Cook"]}


The difference is here, this is clear.



Swift & JSON Data


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.