0

我正在将 JSON 解析到我的 MASTER-DETAIL 应用程序,并且在“深入挖掘”JSON 时遇到问题。我无法在我的detailTableView. 在我的detailTableView中,我想拥有酒店/旅馆的名称,在这种情况下。

查看我的 JSON 和 detailTableView.m:

[

    {
      "title": "Where to stay",
      "pousadas": 
     [
        {
            "beach": "Arrastão",
            "name": "Hotel Arrastão",
            "address": "Avenida Dr. Manoel Hipólito Rego 2097",
            "phone": "+55(12)3862-0099",
            "Email": "hotelarrastao_reserva@hotmail.com",
            "image": "test.jpg",
            "latitude": "-23.753355",
            "longitude": "-45.401946"
       }
    ]
  }

]

以及detailTableView.m中的tableView:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return self.stayGuide.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"detailCellStay"];

以下是我的试训:

    NSString *pous = [self.stayGuide valueForKey:@"name"];

    NSLog([self.stayGuide valueForKey:@"name"]);

    cell.textLabel.text = pous;



    return cell;
}

提前致谢!

4

1 回答 1

2

您正在错误地阅读 JSON!让我们看一下您的数据:

[ <---- array
    { <---- dictionary
        "title": "Where to stay",
        "pousadas": [ <---- array
            { <---- dictionary
                "beach": "Arrastão",
                "name": "Hotel Arrastão",
                "address": "Avenida Dr. Manoel Hipólito Rego 2097",
                "phone": "+55(12)3862-0099",
                "Email": "hotelarrastao_reserva@hotmail.com",
                "image": "test.jpg",
                "latitude": "-23.753355",
                "longitude": "-45.401946"
            }
        ]
    }
]

假设您将数据存储在“stayGuide”属性(应该是 NSArray 类型)中,您可以像这样访问初始字典:

NSDictionary *initialDictionary = [self stayGuide][0]; // access using new Objective-C literals

现在,您可以在此处访问各种值,例如“pousadas”数组。

NSArray *pousadas = initialDictionary[@"pousadas"];

现在,就像我们对初始字典所做的那样,我们可以访问 pousadas 数组中的第一个对象。

NSDictionary *dictionary = pousadas[0];

最后,我们可以在第一个 pousadas 字典中访问其中一些键。

NSString *beach = dictionary[@"beach"];
NSString *name = dictionary[@"name"];
NSString *address = dictionary[@"address"];

NSLog(@"Beach: %@, Name: %@, Address: %@"beach,name,address);

不过,将来您可能希望 stayGuide 属性等于 pousadas 数组。您可以这样设置(其中 initialJSONArray 是您的起始 JSON 数据):

[self setStayGuide:initialJSONArray[0][@"pousadas"]];
于 2013-02-21T23:16:02.207 回答