使用Alamofire在Swift 3中进行Json解析 [英] Json Parsing in swift 3 using Alamofire
问题描述
我正在快速工作3.我是ios的新手.我正在尝试解析json数据,例如
I am working in swift 3. I am new to ios. I am trying to parse the json data like
My jsonVlaue is : {
data = (
{
Password = "@1234";
UserName = "<null>";
"___class" = OrderTable;
"__meta" = "{\"relationRemovalIds\":{},\"selectedProperties\":[\"UserName\",\"created\",\"name\",\"___class\",\"ownerId\",\"updated\",\"objectId\",\"Password\"],\"relatedObjects\":{}}";
created = 1483525854000;
name = TestMan;
objectId = "4316DEBA-78C1-C7BD-FFBC-3CB77D747F00";
ownerId = "<null>";
updated = "<null>";
},
{
Password = 123;
UserName = "<null>";
"___class" = OrderTable;
"__meta" = "{\"relationRemovalIds\":{},\"selectedProperties\":[\"UserName\",\"created\",\"name\",\"___class\",\"ownerId\",\"updated\",\"objectId\",\"Password\"],\"relatedObjects\":{}}";
created = 1483516868000;
name = tommy;
objectId = "29155114-C00B-5E1C-FF6F-7C828C635200";
ownerId = "<null>";
updated = "<null>";
}.......
我只想要键值:名称",并且想要在数组中添加该值.
I want only the keyvalue:"name" and that value I want to add in an Array.
我试图这样做,但是我的应用程序崩溃了.我的代码如下:
I tried to do like that but my app is getting Crash. My code i slike as follows
func getLoginDetails()
{
//https://api.backendless.com/<version>/data/<table-name>/properties
Alamofire.request( HeadersClass.api.domainName + "OrderTable", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: HeadersClass.allHeaders.headers).responseJSON { response in
//debugPrint(response)
if let jsonDict = response.result.value as? NSDictionary {
print("My jsonVlaue is : \(jsonDict)")
let arrayPracticeData: NSArray = jsonDict.value(forKey: "name") as! NSArray
print(arrayPracticeData)
}
}
}
任何人都可以告诉我如何解决此问题.提前致谢.
Can anyone please tell me how to solve this. Thanks in Advance.
推荐答案
首先,在Swift中使用Swift的本机Array和Dictionary
代替NSDictionary
和NSArray
.
First of all in Swift use Swift's native Array and Dictionary
instead of NSDictionary
and NSArray
.
现在要获取名称,您需要从JSON
响应Dictionary
中获取Data
数组.所以尝试这样的事情.
Now to get name you need to get Data
array from your JSON
response Dictionary
. So try something like this.
Alamofire.request( HeadersClass.api.domainName + "OrderTable", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: HeadersClass.allHeaders.headers).responseJSON { response in
//debugPrint(response)
if let jsonDict = response.result.value as? [String:Any],
let dataArray = jsonDict["data"] as? [[String:Any]] {
let nameArray = dataArray.flatMap { $0["name"] as? String }
print(nameArray)
}
}
输出
["TestMan", "tommy", ...]
这篇关于使用Alamofire在Swift 3中进行Json解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!