有两个嵌套字典的字典,然后是数组,然后是字典,我通常如何为目标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"];


现在获取所有密钥:

NSArray *keys= [brandsDict allKeys];


现在,使用您在Array中获得的每个键来相应地获取数据。

09-26 22:56