2011-11-01 50 views
3

我在構建一個使用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中獲取「成分」?

回答

7

你得到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

3

這裏有所有你需要做的:

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