解析iPhone应用上的JSON对象和子元素

问题描述:

我在构建一个使用UPC数据库API的应用程序。我从这里取回一个JSON对象,例如:http://www.simpleupc.com/api/methods/FetchNutritionFactsByUPC.php解析iPhone应用上的JSON对象和子元素

{ 
"success":true, 
"usedExternal":false, 
"result" 
    { 
     "calories_per_serving":"150", 
     "cholesterol_per_serving":"15", 
     "cholesterol_uom":"Mg", 
     "dvp_calcium":"30", 
     "dvp_cholesterol":"4", 
     "dvp_iron":"2", 
     "dvp_protein":"17", 
     "dvp_saturated_fat":"8", 
     "dvp_sodium":"10", 
     "dvp_total_fat":"4", 
     "dvp_vitamin_a":"10"," 
     "dvp_vitamin_c":"0", 
     "dvp_vitamin_d":"25", 
     "fat_calories_per_serving":"25", 
     "fiber_per_serving":"<1", 
     "fiber_uom":"G", 
     "ingredients":"Fat Free Milk, Milk, Sugar, Cocoa (Processed With Alkali), 
         Salt, Carrageenan, Vanillin (Artificial Flavor), 
         Lactase Enzyme, Vitamin A Palmitate And Vitamin D3.", 
     "protein_per_serving":"8", 
     "protein_uom":"G", 
     "size":"240", 
     "units":"mL", 
     "servings_per_container":"8", 
     "sodium_per_serving":"230", 
     "sodium_uom":"Mg", 
     "total_fat_per_serving":"2.5", 
     "total_fat_uom":"G", 
     "trans_fat_per_serving":"0", 
     "trans_fat_uom":"G", 
     "upc":"041383096013" 
    } 
} 

我的问题是与解析“成分”的元素,它是对象字典的子列表。

你会如何建议解析成分列表?如果我能把它交给一个NSArray,假设逗号是分隔符,那就太好了。

我试图做到这一点,但看起来像它只是一个字符串,所以没办法解析它。

任何建议将更受欢迎。谢谢!

//Thats the whole JSON object 
    NSDictionary *json_dict = [theResponseString JSONValue]; 


    //Getting "results" which has all the product info 
    NSArray *myArray = [[NSArray alloc] init]; 
    myArray = [json_dict valueForKey:@"result"]; 

现在我该如何从数组形式的myArray中获取“成分”?

你得到result作为数组,但(在JSON术语中)它是而不是数组。 It's an object, so use an NSDictionary。事情是这样的:

NSDictionary *result = [json_dict objectForKey:@"result"]; 

然后你就可以得到从内ingredients对象:

NSString *ingredients = [result objectForKey:@"ingredients"]; 

编辑按@Bavarious'评论。


道歉明显的错误,因为我不是在Objective-C非常精通。您可能需要为返回的NSDictionaryNSString指针分配内存;我不确定。

+0

谢谢,但我需要一个数组形式的成分,所以我可以访问每个成分。 – TommyG

+0

这一切都很好。不幸的是,为了你的目的,你坚持使用JSON格式。这意味着您首先必须将这些成分作为字符串检索,然后将该字符串在','(逗号)上拆分为数组。我同意JSON格式是愚蠢的,但必须发挥你处理的手。或者,你知道,使用不同的API。 –

+0

基于逗号分割字符串的好方法? – TommyG

这里有所有你需要做的:

NSDictionary *json_dict = [theResponseString JSONValue]; 

// Use a key path to access the nested element. 
NSArray *myArray = [json_dict valueForKeyPath:@"result.ingredients"]; 

编辑

哎呦,马特的权利。以下是如何处理字符串值:

// Use a key path to access the nested element. 
NSString *s = [json_dict valueForKeyPath:@"result.ingredients"]; 
NSArray *ingredients = [s componentsSeparatedByString:@", "]; 

请注意,您可能需要修剪'。'。字符脱离数组的最后一个元素。

+0

仔细看看JSON。 'result.ingredients'不是一个数组。这是一个字符串。 –

+0

不错的尝试 - 本来可以很好,干净,但myArray不是在这种情况下数组 - 它的字符串(也运行“计数”崩溃的应用程序)。 – TommyG

+0

马特是正确的 - 它的一个字符串,所以必须如此蛮力。 – TommyG