再次使用JSON反序列化和IOS(ObjectiveC)

时间:2015-10-27 10:32:35

标签: ios objective-c json

我从JSON反序列化返回此字符串:

extradata: [
      {
        "tourDetails" : {
          "idTour" : 5113123132407808,
          "id" : 5730082031140864,
          "externalNotes" : "nullissimo",
          "name" : "Essential London",
          "description" : "This two-hour walking tour will take you past a great many of London's most important sights as well as along part of the ceremonial route that the Queen followed on her Diamond Jubilee in June 2012. It also leads you past the sites of two events of the glorious 2012 Olympic Games.  The idea of the Essential London Walk is to give you a taster of what is what and where it is. Return later at your leisure to such `icons' as Westminster Abbey, the Houses of Parliament or the London Eye for your own up close and personal visit and inspection. Essential London Walk is the key to learning the fascinating and often surprising background stories to Europe's premier city. This walking tour takes in the most important landmarks in London, including Parliament, Westminster Abbey, Trafalgar Square, Downing Street, Horse Guards Parade, the London Eye, the River Thames and Buckingham Palace.",
          "idLang" : 5629499534213120
        },
        "tour" : {
          "internalNotes" : "no notesssss",
          "id" : 5113123132407808,
          "code" : "BASE-ESS",
          "photoPath" : "http:\/\/cdn.londonandpartners.com\/asset\/c3291aa543a4ae6f15640dd087d8febb.jpg",
          "lon" : -0.1338786,
          "duration" : 2,
          "managedBy" : "omg",
          "type" : 1,
          "place" : "Piccadilly Circus",
          "lat" : 51.5102583,
          "calendarDuration" : 1
        }
      },
      {
        "tourDetails" : {
          "idTour" : 5118084088070144,
          "id" : 5656058538229760,
          "externalNotes" : "prova x vedere una pic",
          "name" : "Amy Winehouse's Camden",
          "description" : "Wander around Camden, following the trail of Amy and her pals",
          "idLang" : 5629499534213120
        },
        "tour" : {
          "internalNotes" : "no notesssss",
          "id" : 5118084088070144,
          "code" : "BASE-",
          "photoPath" : "http:\/\/www.ohmyguidelondon.com\/wp-content\/uploads\/2015\/07\/Dollarphotoclub_21556157.jpg",
          "lon" : -0.133878600000002,
          "duration" : 2,
          "managedBy" : "omg",
          "type" : 1,
          "place" : "Piccadilly Circus",
          "lat" : 51.5102583,
          "calendarDuration" : 1
        }
      },
      {
        "tourDetails" : {
          "idTour" : 5659313586569216,
          "id" : 5634472569470976,
          "externalNotes" : "NOTEPROVA",
          "name" : "Covent Garden Tour",
          "description" : "DESCRIZIONEPROVA",
          "idLang" : 5629499534213120
        },
        "tour" : {
          "internalNotes" : "CODICE PROVA",
          "id" : 5659313586569216,
          "code" : "codprova",
          "photoPath" : "http:\/\/www.ohmyguidelondon.com\/wp-content\/uploads\/2015\/07\/Dollarphotoclub_3313745.jpg",
          "lon" : -0.1232697000000371,
          "duration" : 2.5,
          "type" : 1,
          "place" : "Covent Garden",
          "lat" : 51.5117321,
          "calendarDuration" : 1
        }
      },
      {
        "tourDetails" : {
          "idTour" : 6270652252160000,
          "id" : 5684666375864320,
          "externalNotes" : "",
          "name" : "British museum guided tour",
          "description" : "This walk will take you through the streets of the village of Hampstead with the unique selection of little bars, restaurants and furniture, books and antique shops, and some of the amazing houses and villas owned by film and TV celebrities.\r\n \r\nThen we will make our way and walk through the iconic Heath, one of the largest and popular open spaces in London, with landscape with a series of meadows, woodlands.  On the way we will be seeing the famous 5 ponds, open to the public and included the one for men, women or mixed (bring a towel if you wish to dip in- , experience the wild life (with a touch of luck meet the local squirrels, wild rabbit, foxes, and few others). \r\n \r\nThe great view from Parliament Hill Fields and finishing with the visit of one of the most exclusive ancient mansion right up to the top of the heath, the Kenwood House, the site of the Kenwood summer concert.\r\n \r\nAfter we will be visiting the famous pub \"The Spaniard Inn\" (1585) a favourite stop of the highwaymen but also favourite of Dickens, Joshua Reynolds and Brian Stocker, before heading to London.\r\n \r\nEste tour es tambien disponible en Castellano!\r\n \r\nQuesta passeggiata e' disponibile anche in Italiano\r\n \r\nThe tours starts from Hampstead Tube Station and ends in Archway ( there is a bus ride from the Heath to the tube station)",
          "idLang" : 5629499534213120
        },
        "tour" : {
          "internalNotes" : "Prova British",
          "id" : 6270652252160000,
          "code" : "British museum guided tour",
          "photoPath" : "http:\/\/www.ohmyguidelondon.com\/wp-content\/uploads\/2015\/07\/Dollarphotoclub_86907.jpg",
          "lon" : -0.08584700000000001,
          "duration" : 2,
          "managedBy" : "omg",
          "type" : 1,
          "place" : "British Museum",
          "lat" : 51.510191,
          "calendarDuration" : 1
        }
      }
]

我明白这是一个里面有字典的数组。所以我试图以这种方式检索数据:

NSError *error;
NSDictionary *retData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSDictionary *dic = [retData objectForKey:@"extraData"];

直到这里,一切都好!

但我仍然没有找到一种方法来检索单个数据:tourDetails,tour等...

有人可以帮帮我吗? TKS。

4 个答案:

答案 0 :(得分:2)

这是不正确的:

NSDictionary *dic = [retData objectForKey:@"extraData"];

作为extradata extraData)是一个数组,根据您发布的JSON:

NSArray *arr = retData[@"extradata"];

可以使用快速枚举

枚举每个字典
for (NSDictionary *innerDict in arr) {
    NSDictionary *tourDetails = innerDict[@"tourDetails"];
    NSLog(@"tourDetails=%@", tourDetails);
}

但是,通过评论的外观,您将收到一个字符串对象,而不是一个数组对象。这与您的JSON不匹配,但也许在服务器发生错误的情况下会返回它。您可以使用以下方法处理这两种情况:

id topObject = retData[@"extradata"];
if ([topObject isKindOfClass:[NSArray class]]) {
    NSArray *arr = (NSArray *)topObject;
    // Success; proceed as above
} else {
    NSLog(@"Failed to retrieve JSON data: %@", topObject);
}

答案 1 :(得分:0)

extradata NSArray,其中包含NSDictionaries

NSError *error;
NSDictionary *retData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *array = (NSArray*)[retData objectForKey:@"extraData"];

现在,例如,您希望获得第一个索引中存在的tourDetails或tour。

NSDictionary *dic = [array objectAtIndex:1];
NSDictionary *tourDetailsDic = dic objectForKey:@"tourDetails"];
NSDictionary * tourDic = dic objectForKey:@"tour"];

答案 2 :(得分:0)

您可以通过与NSDictionary相关的其他人NSDictionaryNSArray深入了解json file

NSError *error;
NSDictionary *retData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

NSArray *globalArray = [retData objectForKey:@"extradata"];
for(int i = 0; i < [globalArray count]; i++) {
    NSDictionary *toDisplay = [globalArray objectAtIndex:i];

    // Here is how you retrieve your "tour" and "tourDetails" datas
    NSDictionary *tourDetails = [toDisplay objectForKey:@"tourDetails"];
    NSDictionary *tour = [toDisplay objectForKey:@"tour"];
    NSLog([NSString stringWithFormat:@"tour: %@\ntourDetails: %@", tour, tourDetails]);
}

答案 3 :(得分:0)

好的..我发现问题和解决方案: 问题:从服务器返回的数据充满了“\”符号。因此它不能作为结构读取,而只是作为字符串读取。 解决方案:解决方案是双重反序列化:

NSDictionary *retData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *retStr = [retData objectForKey:@"extraData"];
NSData *newData = [retStr dataUsingEncoding:NSUTF8StringEncoding];
NSArray *json = [NSJSONSerialization JSONObjectWithData:newData options:kNilOptions error:&error];

只有在此操作之后,我才能访问“真实”结构:

NSDictionary *newDict = [json objectAtIndex:0];
NSString *test = [[newDict objectForKey:@"tour"] objectForKey:@"id"];

感谢所有贡献者和f ** k向所有人投票给我:这是一个真正的问题,现在已经解决了!

再见