Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing JSON object and sub-elements on iphone app

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

{
"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.

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?

like image 450
TommyG Avatar asked Dec 06 '25 10:12

TommyG


1 Answers

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

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

Then you can get the inner ingredients object from that:

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

Edited as per @Bavarious' comment.


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

like image 170
Matt Ball Avatar answered Dec 08 '25 01:12

Matt Ball



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!