我尝试将此JSON数据转换为Dictionary
,但我不知道如何在此JSON中构建数据。我认为我的代码检测JSON结构是错误的。
JSON响应
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 2,
"id": 2,
"title": "et ea vero quia laudantium autem",
"body": "delectus reiciendis molestiae occaecati non minima eveniet qui voluptatibus\naccusamus in eum beatae sit\nvel qui neque voluptates ut commodi qui incidunt\nut animi commodi"
}
]
这是我的代码:
enum postResult {
case Success([Post]) //return array of post
case Failure(ErrorType)
//
func postsFromJSONData(data:NSData)->PhotosResult{
do {
let jsonObject : AnyObject = try NSJSONSerialization.JSONObjectWithData(data,options:[])
guard let jsonDictionary = jsonObject as? [NSObject:AnyObject],
postsArray = ["userId"] as? [[String:AnyObject]] else {
return.Failure(InvalidError.InvalidJSONData)
}
var finalPosts = [post]()
return.Success(finalPosts)
}
catch let error {
return.Failure(error)
}
}
}
答案 0 :(得分:3)
您的回复是数组而非字典,因此您需要从数组访问对象,而您的userId
键包含的数字不是Array/Dictionary
。
let jsonObject = tryNSJSONSerialization.JSONObjectWithData(data,options:[]) as! [[String: AnyObject]]
if jsonObject.count > 0 {
if let userId = jsonObject[0]["userId"] as? Int {
print(userId)
}
}