如何解析json值中的动态更改。字典与2嵌套dic&然后阵列然后再次dic

时间:2015-03-20 05:18:47

标签: ios objective-c json nsarray nsdictionary

带有两个嵌套字典的字典,然后是数组,然后是字典,我怎样才能为目标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"
            },

1 个答案:

答案 0 :(得分:1)

正如我所看到的,您的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(响应数据)的NSDictionary,如下所示:

NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];

创建品牌词典

NSDictionary *brandsDict = [jsonDictionary objectForKey:@"brands"];

现在获取所有密钥:

NSArray *keys= [brandsDict allKeys];

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