Reputation: 1176
I am try to convert this JSON data into Dictionary
, but I don't know how the data will be structured in this JSON. I think my code for detect JSON struct thats wrong.
JSON Response
[
{
"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"
}
]
Thats my code :
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)
}
}
}
Upvotes: 0
Views: 127
Reputation: 72410
Your response is Array not Dictionary, so you need to access object from Array also your userId
key contains number as value not 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)
}
}
Upvotes: 3