解析iphone应用程序上的JSON对象和子元素

Tom*_*myG 3 arrays iphone xcode json ios

我正在构建一个使用UPC数据库API的应用程序.我回到了一个JSON对象,例如:http://www.simpleupc.com/api/methods/FetchNutritionFactsByUPC.php

{
"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"
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是解析"ingredients"元素,它是对象字典的子列表.

您如何建议解析成分列表?如果我能把它送到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"];
Run Code Online (Sandbox Code Playgroud)

现在我如何以数组形式从myArray中获取"成分"?

Mat*_*all 7

你得到的result是一个数组,但是(在JSON术语中)它不是一个数组.这是一个对象,所以使用一个NSDictionary.这样的事情:1

NSDictionary *result = [json_dict objectForKey:@"result"];
Run Code Online (Sandbox Code Playgroud)

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

NSString *ingredients = [result objectForKey:@"ingredients"];
Run Code Online (Sandbox Code Playgroud)

根据@Bavarious的评论编辑.


1对于明显的错误道歉,因为我对Objective-C并不十分精通.您可能需要为返回的NSDictionaryNSString指针分配内存; 我不确定.