My Code:
var nameArray = [String]()
do
{
let arrayValues = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
print(arrayValues.count)
print(arrayValues)
let limit = arrayValues.count-1
for i in 0...limit
{
let x = i
let dataValues = arrayValues.object(forKey: "result" ) as! NSDictionary // shows error
print(dataValues)
let name = dataValues.object(forKey: "description")
self.nameArray.insert(name as! String, at: x)
}
来自网络服务的响应
{
"result": [
{
"id": "1",
"title": "Mental Health",
"description": "<p>Mental health</p>",
"date": "22 Jul 2015",
"image": "image1444714284.jpg",
"status": "0"
},
{
"id": "2",
"title": "Olive oil: The healthiest fat is also harmful for you",
"description": "<p>ssss</p>",
"date": "16 Jul 2015",
"image": "image1444714355.jpg",
"status": "1"
},
{
"id": "3",
"title": "Jogging:Find the best fitness friend",
"description": "<p>ji</p>",
"date": "16 Jul 2015",
"image": "image1444714465.jpg",
"status": "1"
},
{
"id": "4",
"title": "Stock up on these",
"description": "<p>fffffffff</p>",
"date": "15 Jul 2015",
"image": "image1444715133.jpg",
"status": "1"
},
{
"id": "5",
"title": "Pick your perfect tunes",
"description": "<p>fffffffff</p>",
"date": "15 Jul 2015",
"image": "image1444715295.jpg",
"status": "0"
},
{
"id": "6",
"title": "Buy comfy sneaks",
"description": "<p>h</p>",
"date": "22 Jul 2015",
"image": "image1444715388.jpg",
"status": "1"
},
{
"id": "7",
"title": "Eat this, run that",
"description": "<p>rrrrrr</p>",
"date": "9 Jul 2015",
"image": "image1444715465.jpg",
"status": "1"
},
{
"id": "8",
"title": "Say hello to H20",
"description": "<p>jkjk</p>",
"date": "10 Jul 2015",
"image": "image1444715515.jpg",
"status": "1"
},
{
"id": "11",
"title": "gfhsh",
"description": "<p>sdhsgh fgdfgdgdf</p>",
"date": "17 Dec 2015",
"image": "image1450263806.jpg",
"status": "1"
},
{
"id": "12",
"title": "test",
"description": "<p>dfsdfsdffds</p>",
"date": "16 Dec 2015",
"image": "image1450264678.jpg",
"status": "1"
}
],
"status": true,
"message": "Health Tips List..."
}
试试这个
var desriptionArray = [String]()
for dataValues in responseObject["result"] as! [[String: AnyObject]] {
let name = dataValues ["description"] as! String
desriptionArray .append(name)
}
或
for (index , element) in (responseObject["result"] as! [Any]).enumerated() {
let nameDict = element as! [String : AnyObject]
let strDecription = nameDict["description"] as! String
desriptionArray .insert(strDecription, at: index)
}