带有两个嵌套字典的字典,然后是数组,然后再次是字典,我如何为 Objective C ,iOS 8 编写一般代码;
{
"brands": {
"Clinique": {
"Foundation": {
"Even Better Makeup SPF 15": {
"productName": "Even Better Makeup SPF 15",
"colors": [
{
"id": "30816",
"client_id": "1422956000sjdaC",
"product_id": "190",
"shade_name": "Alabaster",
"shade_code": "#F0C9AE",
"color_id": null,
"image_url": "",
"price": "",
"offer": "",
"created_by": "1422956000sjdaC",
"created_date": "2015-03-06",
"sku_id": "",
"product_web_url": "",
"brand_id": "Clinique",
"product_name": "Even Better Makeup SPF 15",
"makeup_type": "Foundation",
"color_family": "cool"
},
最佳答案
正如我所见,您的 JSON 响应正在发送产品详细信息,因此
"brands": {
"Clinique": {
"Foundation": {
始终保持不变,下面的响应会根据产品而变化。
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *productsDict = [[jsonDictionary objectForKey:@"brands"] objectForKey:@"Clinique"] objectForKey:@"Foundation"];
NSArray *keys=[productsDict allKeys];
for (int i = 0; i < keys.count; i++) {
NSDictionary *prodSingle = [productsDict objectForKey:[NSString StringWithFormat:@"%@",keys[i]]];
}
现在你有了 prodSingle,用它来获取每个产品的数据。
注意:未经测试,如果不起作用,我将提供经过测试的版本。
编辑:
正如您所说,只有 brands
键将保持不变,其他键将动态变化,
你应该这样做:
所以你可以做的是使用 jsonData(response data) 创建一个 NSDictionary,如下所示:
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
创建品牌字典
NSDictionary *brandsDict = [jsonDictionary objectForKey:@"brands"];
现在获取所有 key :
NSArray *keys= [brandsDict allKeys];
现在使用数组中获得的每个键来相应地获取数据。
关于ios - 如何解析json值的动态变化。带有 2 个嵌套字典的字典,然后是数组,然后再次挖掘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29159902/