1,swiftyjson Introduction and Configuration
Swiftyjson is an open source library that is written in the swift language, allowing us to easily process JSON data (parse data, generate data).
GitHub Address: Https://github.com/SwiftyJSON/SwiftyJSON
Use configuration: Direct Swiftyjson.swift added to the project.
Advantages of 2,swiftyjson
Compared to Nsjsonserializationswiftyjson, when you get the JSON data for a multi-level structure. Swiftyjson do not have to always determine whether this node exists, is not the class we want, the next node exists, is not the class we want .... At the same time, the Swiftyjson internally automatically optional (optional type) of the unpacking (wrapping), greatly simplifying the code.
(1) For example, we have one of the following JSON data that represents a collection of contacts:
[
{
"Name": "Hangge",
"Age": 100,
"Phones": [
{
"Name": "Company",
"Number": "123456"
},
{
"Name": "Family",
"Number": "001"
}
]
},
{
"Name": "Big Boss",
"Age": 1,
"Phones": [
{
"Name": "Company",
"Number": "111111"
}
]
}
]
To facilitate test comparisons, we first convert the JSON-formatted string to NSData:
Let Jsonstr = "[{] name\": \ "hangge\", "age\": "," "phones\": [{\ "name\": \ "Company \", \ "Number\": \ "123456\"}, "name\": \ " Family \ ", \" Number\ ": \" 001\ "}}, {\" name\ ": \" Big boss\ ", \" age\ ": 1,\" phones\ ": [{\ name\]: \" Company \ ", \" Number\ ": \" 111111\ "} ]}]"
If Let Jsondata = jsonstr.datausingencoding (nsutf8stringencoding,
Allowlossyconversion:false) {
//.........
}
(2) Using Nsjsonserializationswiftyjson parsing
For example, we want to take the first contact person's first phone number, each level is very difficult to judge, the code is as follows:
If let Userarray = try? Nsjsonserialization.jsonobjectwithdata (Jsondata,
Options:. allowfragments) as? [[String:anyobject]],
Let phones = Userarray? [0] ["Phones"] as? [[String:anyobject]],
Let number = phones[0]["number"] as? String {
Find phone number
Print ("First phone number for first contact:", numbers)
}
Even if you use optional to simplify, there are a lot of code:
If let Userarray = try? Nsjsonserialization.jsonobjectwithdata (Jsondata,
Options:. allowfragments) as? [[String:anyobject]],
Let number = (userarray?[ 0]["Phones"] as? [[String:anyobject]])? [0] ["Number"]
As? String {
Find phone number
Print ("First phone number for first contact:", numbers)
}
(3) Use Swiftyjson Resolution:
You don't have to worry about arrays, you don't have to judge the nodes, what you're unpacking, the code is as follows:
Let JSON = JSON (data:jsondata)
If let number = json[0]["Phones"][0]["number"].string {
Find phone number
Print ("First phone number for first contact:", numbers)
}
If you do not get the value, you can go to the error processing, print a look at what is wrong:
Let JSON = JSON (data:jsondata)
If let number = json[0]["Phones"][0]["number"].string {
Find phone number
Print ("First phone number for first contact:", numbers)
}else {
Printing error messages
Print (json[0]["Phones"][0]["number"])
}
3, get network data, and use Swiftyjson parsing
In addition to parsing local JSON data, we actually get remote data and parse it more often through URL addresses.
(1) combined with nsurlsession
Creating Nsurl Objects
Let urlstring:string= "http://www.111cn.net/getJsonData.php"
Let url:nsurl! = Nsurl (string:urlstring)
Create a Request object
Let request:nsurlrequest = Nsurlrequest (Url:url)
Let session = Nsurlsession.sharedsession ()
Let Datatask = session.datataskwithrequest (Request,
Completionhandler: {(data, response, error)-> Void in
If error!= nil{
Print (error?). Code
Print (error?). Description
}else{
Let JSON = JSON (data:data!)
If let number = json[0]["Phones"][0]["number"].string {
Find phone number
Print ("First phone number for first contact:", numbers)
}
}
}) as Nsurlsessiontask
To start a task by using the Resume method
Datatask.resume ()
(2) combined with Alamofire
Creating Nsurl Objects
Let urlstring:string= "http://www.111cn.net/code/test.php"
Let url:nsurl! = Nsurl (string:urlstring)
Alamofire.request (. Get, URL). Validate (). Responsejson {response in
Switch Response.result {
Case. Success:
If let value = Response.result.value {
Let JSON = JSON (value)
If let number = json[0]["Phones"][0]["number"].string {
Find phone number
Print ("First phone number for first contact:", numbers)
}
}
Case. Failure (let error):
Print (Error)
}
}
4, get the value
(1) Optional value acquisition (Optional getter)
Through. Number,. String,. bool,. int,. UInt,. Float,. Double,. Array,. Dictionary, int8, Uint8, Int16, Uint16, Int32, Uint32, Int64, Uint64 and other methods to obtain the optional value, we need to determine whether there is, and do not exist can get the specific error message.
Int
If let-age = json[0][' age '].int {
Print (age)
} else {
Printing error messages
Print (json[0]["age"])
}
String
If let name = json[0]["Name"].string {
Print (name)
} else {
Printing error messages
Print (json[0]["name"])
}
(2) Non-optional value acquisition (Non-optional getter)
Use properties such as Xxxvalue to get the value and return a default value if not obtained. Lest we should judge the unpacking again.
If not a number or nil, return 0
Let Age:int = json[0][' age '].intvalue
If not a String or nil, return ""
Let name:string = json[0]["Name"].stringvalue
If not a Array or nil, return []
Let list:array<json> = json[0]["Phones"].arrayvalue
If not a Dictionary or nil, return [:]
Let phone:dictionary<string, json> = json[0]["Phones"][0].dictionaryvalue
(3) Get raw data (Raw object)
Let Jsonobject:anyobject = Json.object
If let Jsonobject:anyobject = Json.rawvalue
JSON converted to NSData
If let data = Json.rawdata () {
Do something your want
}
JSON converts to string string
If let string = Json.rawstring () {
Do something your want
}
5, set the value
json[0]["Age"].int = 101
json[0]["name"].string = "111cn.net"
json[0]["Phones"].arrayobject = [["Name": "Fixed", "number": 110],["name": "Mobile", "number": 120]]
json[0]["Phones"][0].dictionaryobject = ["Name": "Fixed", "number": 100]
6, subscript access (subscript)
You can access the hierarchy and properties of JSON data by numbers, strings, and array-type subscripts. For example, the results of the following three ways are the same:
Mode 1
Let number = json[0]["Phones"][0]["number"].stringvalue
Mode 2
Let number = json[0, "Phones", 0, "number"].stringvalue
Mode 3
Let keys:[jsonsubscripttype] = [0, "Phones", 0, "number"]
Let number = Json[keys].stringvalue
7, loop through all the data in the JSON object
(1) If the JSON data is an array type
for (Index,subjson):(String, JSON) in JSON {
Print ("\ (index): \ (Subjson)")
}
(2) If the JSON data is a dictionary type (Dictionary)
for (Key,subjson):(String, JSON) in json[0] {
Print ("\ (key): \ (Subjson)")
}
8, construct a JSON object to create data
(1) Empty JSON object
Let Json:json = Nil
(2) Create a JSON object with a simple data type
Stringliteralconvertible
Let Json:json = "I ' m a son"
Integerliteralconvertible
Let Json:json = 12345
Booleanliteralconvertible
Let Json:json = True
Floatliteralconvertible
Let Json:json = 2.8765
(3) using array or dictionary data to create a JSON object
Dictionaryliteralconvertible
Let Json:json = ["I": "AM", "a": "Son"]
Arrayliteralconvertible
Let Json:json = ["I", "AM", "a", "son"]
Array & Dictionary
var Json:json = ["Name": "Jack", "Age": "+", "list": ["a", "B", "C", ["What": "This"]]]
json["List"][3]["what"] = "that"
json["List", 3, "what"] = "that"
Let path = ["List", 3, "what"]
Json[path] = "that"