xcode 在 iPhone 应用程序上解析 JSON 对象和子元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7974212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 22:18:16  来源:igfitidea点击:

parsing JSON object and sub-elements on iphone app

iphoneiosarraysxcodejson

提问by TommyG

I am building an app that uses a UPC data base API. I am getting back a JSON object, example from here: http://www.simpleupc.com/api/methods/FetchNutritionFactsByUPC.php

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

My problem is with parsing the "ingredients" element, which is a sub list of the object dictionary.

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

How would you suggest parsing the ingredients list? If I could get it to an NSArray, assuming commas are separators, that would have been great.

您建议如何解析成分列表?如果我能把它放到 NSArray 中,假设逗号是分隔符,那就太好了。

I tried to do this, but looks like its just a string, so no way to parse it.

我试图这样做,但看起来它只是一个字符串,所以无法解析它。

Any suggestion would be more than welcome. Thanks!

任何建议都非常受欢迎。谢谢!

   //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"];

Now how do I get "ingredients" from myArray in an array form?

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

回答by Matt Ball

You're getting resultas an array, but (in JSON terminology) it's notan array. It's an object, so use an NSDictionary. Something like this:1

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

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

Then you can get the inner ingredientsobject from that:

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

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

Editedas per @Bavarious' comment.

根据@Bvarious 的评论进行编辑



1Apologies for glaring errors, as I'm not terribly well-versed in Objective-C. You might need to allocate memory for the returned NSDictionaryand NSStringpointers; I'm not sure.

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

回答by jlehr

Here's all you need to do:

这是您需要做的所有事情:

 NSDictionary *json_dict = [theResponseString JSONValue];

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

EDIT

编辑

Whoops, Matt's right. Here's how to deal with the string value:

哎呀,马特是对的。下面是如何处理字符串值:

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

Note that you might need to trim the '.' character off the last element of the array.

请注意,您可能需要修剪“.” 数组的最后一个元素的字符。