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

标签 iphone ios arrays xcode json

我正在构建一个使用 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"
    }
}

我的问题是解析“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"];

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

最佳答案

您得到的 result 是一个数组,但(在 JSON 术语中)它不是数组。 It's an object, so use an NSDictionary .像这样:1

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

然后您可以从中获取内部 ingredients 对象:

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

根据@Bavarious 的评论编辑


1对于明显的错误表示歉意,因为我对 Objective-C 不是很精通。您可能需要为返回的 NSDictionaryNSString 指针分配内存;我不确定。

关于iphone - 在 iphone 应用程序上解析 JSON 对象和子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7974212/

相关文章:

iphone - EXC_BAD_ACCESS(Code=1…. 当使用 NSObject 作为委托(delegate)时

ios - 在 viewWillAppear 中调用 performFetch 不起作用

iphone - NSTimer 未按预期运行

iphone - ivar 在两个街区内

ios - ViewController 容器 UIView 的大小

android - Flutter MaterialPageRoute导航到黑色背景的屏幕时如何解决?

C变量 "forgets"接受输入后的值是多少

java - 在Java中将列表转换为数组

c - 解码数组

iPhone SDK - 另一个控件内的相对位置?