-1

通常我会读取包装在“数据”顶级项目中的 json。但在下面的例子中,没有顶级“数据”项。

 [
      {
        "AreaName": null,
        "AreaId": 0,
        "DestinationName": "Alanya",
        "DestinationId": 14,
        "CountryName": "Tyrkiet",
        "CountryId": 15
      },
      {
        "AreaName": null,
        "AreaId": 0,
        "DestinationName": "Antalya",
        "DestinationId": 113,
        "CountryName": "Tyrkiet",
        "CountryId": 15
      }
 ]

通常我会做类似的事情

NSDictionary *temp = [[MyArray1 objectAtIndex:0]valueForKey:@"Data"];

但这在这种情况下不起作用。在像这样的匿名 JSON 对象的情况下,我将如何遍历元素?

4

4 回答 4

4

1.) 首先使用上面的字符串创建 NSMutableArray

 jsonArray = [NSJSONSerialization JSONObjectWithData:data
                                                               options:0
                                                                 error:&error];

2.) 然后循环这个数组中的所有对象。

for(NSMutableDictionary *dictionary in jsonArray){
 NSString *name=[dictionary objectForKey:@"AreaName"];
 //and so on.
}
于 2013-05-01T11:20:17.320 回答
0

尝试

//JSON data from webservice
id json = ...
NSArray *areas = nil;
if ([json isKindOfClass:[NSDictionary class]]) {

   areas = json[@"Data"];

}else if ([json isKindOfClass:[NSArray class]])
{
    areas = json;
}

[areas enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
     //Enumerate
}];
于 2013-05-01T11:23:50.427 回答
0

首先你必须从https://github.com/stig/json-framework/下载 JSON 框架

并在您的班级顶部导入 JSON.h。然后执行以下代码:

NSArray *arr = [responseString JSONValue];

    NSLog(@"JSOn arr count : %d",[arr count]);

    for (int i =0;i< [arr count]; i++) {

    NSDictionary *dicObj = [arr objectAtIndex:i];

    NSString *strAreaName = (NSString*) [dicObj objectForKey:@"AreaName"];
    int areaID = [dicObj objectForKey:@"AreaId"];
    NSString *strDestinationName = (NSString*) [dicObj objectForKey:@"DestinationName"];
int destID = [dicObj objectForKey:@"DestinationId"];
    NSString *strCountryName = (NSString*) [dicObj objectForKey:@"CountryName"];
    int countryID = [dicObj objectForKey:@"CountryId"];

    }

希望能帮助到你。

于 2013-05-01T11:45:21.743 回答
0

在你的情况下, json 不是字典,而是一个数组,所以

NSMutableArray *response = [[NSString stringWithContentsOfURL:[NSURL URLWithString:requestUrlString] encoding:NSUTF8StringEncoding error:NULL] JSONValue];

for(NSDictionary *dictionary in response)
{
     NSLog(@"Data Dictionary is : %@",dictionary);
}
于 2013-05-01T11:21:12.957 回答