Reprinted from: http://www.cnblogs.com/theswiftworld/p/4660177.html
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 that the difference between a string type and a numeric type, the value of the string type is enclosed in a pair of double quotes, 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": "shower",
"icon": "09d"
},
{
"id": 701,
"main": "Mist",
"description": "Mist",
"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=en_US"
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.
- First, we pass Let url = Nsurl (string:apiurl) The weather interface is packaged as Nsurl.
- then we use let jsondata = NSData (contentsofurl:url) Download the contents of this URL and store it in NSDatain .
-
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.
-
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:
- MutableContainers: Lets you change the array and dictionary in the JSON data that is returned.
- AllowFragments: Allows data returned by JSON to have multiple root nodes.
- 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.
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 the 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
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 to resolve successfully.
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.
Other programmes
Of course, in addition to using nativeNSJSONSerializationto process json, we can also use a number of third-party libraries for JSON data operations, such as: Swiftyjson, Argo.
Confined to the length of our reading and fatigue period, this article only describes the native way. The follow-up will also provide a more detailed explanation of the use of these third-party libraries, as well as their benefits and weaknesses.
Here is the corresponding file of this articleplayground, you should be able to download it should be a better reference:
Swift-json.playground
Swift and JSON data