我對iOS開發非常陌生,我有一個問題來解析來自API的JSON響應。解決JSON的Swift問題:無法將'__NSCFDictionary'類型的值轉換爲'NSArray'錯誤
這裏是我的示例JSON看起來像:
{
"recipe":{
"publisher":"Real Simple",
"f2f_url":"http://food2fork.com/view/39999",
"ingredients":[
"1 tablespoon olive oil",
"1 red onion, chopped",
"2 small yellow squash, cut into 1/2-inch pieces",
"2 cloves garlic, chopped",
"1 jalapeo, seeded and thinly sliced",
"1 kosher salt and black pepper",
"4 28-ounce can diced tomatoes\n"
],
"source_url":"http://www.realsimple.com/food-recipes/browse-all-recipes/halibut-spicy-squash-tomatoes-00000000006842/index.html",
"recipe_id":"39999", "image_url":"http://static.food2fork.com/someurl.jpg",
"social_rank":95.14721536803285,
"publisher_url":"http://realsimple.com",
"title":"Halibut With Spicy Squash and Tomatoes"
}
}
,當我打印JSON(另一個在這個例子中)它看起來像這樣:
["recipe": {
"f2f_url" = "http://food2fork.com/view/20970";
"image_url" = "http://static.food2fork.com/98113574b0.jpg";
ingredients = (
"1 (170 gram) can crabmeat",
"125 grams PHILADELPHIA Light Brick Cream Cheese Spread, softened",
"2 green onions, thinly sliced",
"1/4 cup MIRACLE WHIP Calorie-Wise Dressing",
"12 wonton wrappers"
);
publisher = "All Recipes";
"publisher_url" = "http://allrecipes.com";
"recipe_id" = 20970;
"social_rank" = "41.83825995815504";
"source_url" = "http://allrecipes.com/Recipe/Philly-Baked-Crab-Rangoon/Detail.aspx";
title = "PHILLY Baked Crab Rangoon";
}]
我有一個對象配方和它看起來像這樣:
class Recipe {
struct Keys {
static let Title = "title"
static let ImageUrl = "image_url"
static let Ingredients = "ingredients"
static let RecipeId = "recipe_id"
}
var title : String? = nil
var id = 0
var imageUrl : String? = nil
var ingredients : String? = nil
init(dictionary : NSDictionary) {
self.title = dictionary[Keys.Title] as? String
self.id = dictionary[RecipeDB.Keys.ID] as! Int
self.imageUrl = dictionary[Keys.ImageUrl] as? String
self.ingredients = dictionary[Keys.Ingredients] as? String
}
}
當我嘗試解析JSON並將其轉換爲字典時,我得到一個這裏錯誤
是我的方法是投響應字典和導致錯誤
func recipiesFromData(data: NSData) -> [Recipe] {
var dictionary : [String : AnyObject]!
dictionary = (try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments))
as! [String : AnyObject]
let recipeDictionaries = dictionary["recipe"] as! [[String : AnyObject]]
let recipies = recipeDictionaries.map() { Recipe(dictionary: $0) }
return recipies
}
感謝。
這看起來不像是有效的JSON – njuri
這不是原始的JSON,看起來像一個'print'解析後的JSON。 – Rob
爲什麼要將nsdictionary轉換爲nsarray? –