繁体   English   中英

需要帮助来解析JSON

[英]Need help for parsing JSON

我正在学习如何解析JSON。 我已经完成了raywenderlich教程,但是我仍然迷失了一些步骤。 我有自己的JSON:

{
    "Albumvideo":{
        "album01":{
            "titreAlbum":"Publicité",
            "photoAlbum":"blabla.jpg",
            "pubVideos":{
                "pub01":[
                {
                "titrePub":"Chauffage Compris",
                "dureePub":"01'25''",
                "photoPub":"chauffage.jpg",
                "lienPub":"http://www.wmstudio.ch/videos/chauffage.mp4"
                }
                ]
            }
        },
        "album02":{
            "titreAlbum":"Events",
            "photoAlbum":"bloublou.jpg",
            "eventsVideos":{
                "event01":[
                {
                "titreEvent":"Chauffage Compris",
                "dureeEvent":"01'25''",
                "photoEvent":"chauffage.jpg",
                "lienEvent":"http://www.wmstudio.ch/videos/chauffage.mp4"
                }
                ]
            }
        }
    }
}

我得到了我的“代码”来解析我的JSON:

- (void) viewDidLoad
{
    [super viewDidLoad];

    dispatch_async (kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL:lienAlbumsVideo];
        [self performSelectorOnMainThread:@selector(fetchedData:)withObject:data waitUntilDone:YES];
    });
}
- (void)fetchedData:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    NSArray* albumsVideo = [json objectForKey:@"Albumvideo"];

    NSLog(@"Nombre d'albums : %i",[albumsVideo count]);

}

这工作正常,我的NSLog返回'2'。 我现在遇到困难的地方是使用例如“ titreAlbum”或“ event01”创建数组。 如果我做 :

NSArray* event01 = [json objectForKey:@"event01"];
NSLog(@"Number of objects in event01 : %i ", [event01 count]);

我的NSLog返回“ 0”。

我真的不明白如何从JSON中的多维数组解析信息。 谢谢了!

尼古拉斯

您没有二维数组。 JSON不支持此功能,但支持数组数组(如C和Objective-C一样)。

NSDictionary *document = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

// Getting titreAlbum
NSDictionary *albumVideo = document[@"Albumvideo"];

NSDictionary *album01 = albumVideo[@"album01"];

NSString *titreAlbum = album01[@"titreAlbum"];

// Getting an event

NSDictionary *album02 = albumVideo[@"album02"];
NSDictionary *eventVideos = album02[@"eventsVideos"];
NSArray *event01 = eventVideo[@"event01"];

(在Safari中输入)

如果您对中间层不感兴趣,也可以使用KVC。

但是我的标识符和问题让我认为,JSON的结构格式错误。

有些事情,每次看到

{...}

NSDictionary开头/结尾的json NSDictionary

一旦解析,而

[...]

NSArray的开始端。

因此,一旦您使用NSJSONSerialization解析了json,就可以使用该知识浏览该字典。

给定json,您必须获取"titreAlbum"数组,您必须执行以下操作:

NSDictionary *albumVideo = json[@"Albumvideo"];
NSMutableArray *albumTitres = [[NSMutableArray alloc] init];
for (NSDictionary *album in albumVideo) {
    [albumTitres addObject:album[@"titreAlbum"]];
}

就是说,我认为您的json不会像通过JSONLint验证那样​​格式错误,但是并不能帮助您解析它。 我希望Albumvideo是一个专辑数组,而不是一个词典字典。

我遇到过同样的问题。 我实际上是在尝试获取需要的Google Distance API

{
 "routes" : [
  {
     "bounds" : {
        "northeast" : {
           "lat" : 23.0225066,
           "lng" : 73.2544778
        },
        "southwest" : {
           "lat" : 19.0718263,
           "lng" : 72.57129549999999
        }
     },
     "copyrights" : "Map data ©2014 Google",
     "legs" : [
        {
           "distance" : {
              "text" : "524 km",
              "value" : 523839
           },
           "duration" : {
              "text" : "7 hours 34 mins",
              "value" : 27222
           },
           "end_address" : "Mumbai, Maharashtra, India",
           "end_location" : {
              "lat" : 19.0759856,
              "lng" : 72.8776573
           },
           "start_address" : "Ahmedabad, Gujarat, India",
           "start_location" : {
              "lat" : 23.0225066,
              "lng" : 72.57129549999999
           },
           "steps" : [
              {
                 "distance" : {
                    "text" : "0.2 km",
                    "value" : 210
                 },
                 "duration" : {
                    "text" : "1 min",
                    "value" : 25
                 },
                 "end_location" : {
                    "lat" : 23.0226436,
                    "lng" : 72.573224
                 },
                 "html_instructions" : "Head on Swami Vivekananda RdRoad/Swami Vivekananda Rd",
                 "polyline" : {
                    "points" : "uqokCsa}yLS?GYEk@Cq@@qA@eA@aADm@"
                 },
                 "start_location" : {
                    "lat" : 23.0225066,
                    "lng" : 72.57129549999999
                 },
                 "travel_mode" : "DRIVING"
              }]`

我需要访问routes.legs.steps.html_instructions。

所以我的代码如下

NSURL *url=[[NSURL alloc] initWithString:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=ahmedabad&destination=%@",self.city]];`

NSURLResponse *res;
NSError *err;

NSData *data=[NSURLConnection sendSynchronousRequest:[[NSURLRequest alloc] initWithURL:url] returningResponse:&res error:&err];

NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

NSArray *routes=dic[@"routes"];
NSArray *legs=routes[0][@"legs"];
NSArray *steps=legs[0][@"steps"];
NSMutableArray *textsteps=[[NSMutableArray alloc] init];
NSMutableArray *latlong=[[NSMutableArray alloc]init];

for(int i=0; i< [steps count]; i++){
    NSString *html=steps[i][@"html_instructions"];
    [latlong addObject:steps[i][@"end_location"]];
    [textsteps addObject:html];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM