我在構建一個使用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中獲取「成分」?
謝謝,但我需要一個數組形式的成分,所以我可以訪問每個成分。 – TommyG
這一切都很好。不幸的是,爲了你的目的,你堅持使用JSON格式。這意味着您首先必須將這些成分作爲字符串檢索,然後將該字符串在','(逗號)上拆分爲數組。我同意JSON格式是愚蠢的,但必須發揮你處理的手。或者,你知道,使用不同的API。 –
基於逗號分割字符串的好方法? – TommyG