【发布时间】:2015-12-08 20:10:13
【问题描述】:
我是 iOS 开发的新手,在解析来自 API 的 JSON 响应时遇到问题。
这是我的示例 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 并将其转换为字典时,我收到 Could not cast value of type '__NSCFDictionary' to 'NSArray' 错误
这是我将响应转换为字典并导致错误的方法
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。
-
那不是原始的 JSON。这看起来像是解析后的 JSON 的
print。 -
为什么要将 nsdictionary 转换为 nsarray ?
-
是的,这是 JSON 的打印,我将编辑我的帖子并给出另一个 JSON 示例