1

我已经完成了关于 iOS 中 JSON 的 Raywenderlich 教程,但是我很难将它适应我自己的 JSON 文件。这是我的 JSON

{
    "Albumvideo":[
    {
        "titre": "Publicité",
        "photo":"blabla.jpg"
    },
    {
        "titre": "Events",
        "photo":"blabla.jpg"
    }
    ]
}

这是我的代码

- (void) viewDidLoad
{
    [super viewDidLoad];
    dispatch_async (kBgQueue, ^{
         NSData* data = [NSData dataWithContentsOfURL:lienAlbumsVideo];
        [self performSelectorOnMainThread:@selector(fetchedData:)withObject:data waitUntilDone:YES];
    });
}

- (void)fetchedData:(NSData *)responseData {
     NSError* error;
     NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
     NSArray* albumsvideo = [json objectForKey:@"titre"];
     NSLog(@"Album: %@", albumsvideo);
}

日志返回null

4

3 回答 3

12

你这样做是不对的。json您已在字典(名为)中正确填写了 JSON 数据。但是,您的 Main中有一个Array of Dictionaries(称为) ,而 of 的值在Array 中。AlbumvideoDictionarytitreAlbumvideo

正确的代码是:

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray* albumsvideo = [json objectForKey:@"Albumvideo"];
NSString *titre1 = [[albumsvideo objectAtIndex:0]valueForKey:@"titre"];
NSString *titre2 = [[albumsvideo objectAtIndex:1]valueForKey:@"titre"];

理解概念。这取决于你的JSON. 如果它是一个数组(里面的值[ ]),那么你必须保存NSArray,如果它是一个字典(里面的值{ })然后另存为NSDictionary,如果你有像字符串、整数、双精度这样的单个值,那么你必须使用适当的 Objective-C 数据来保存它们类型。

希望您对JSON Parsing有一些正确的认识。

于 2013-06-10T14:07:18.927 回答
1

Vin的回答是对的。基本上,要解析 json 响应,请查看使用的括号类型。

从外部符号开始解析并检查符号。如果是,
1){那么它就是 NSDictionary。
2)[然后它是NSArray。

这些简单的规则将使您的生活变得轻松。:)

于 2013-06-10T14:28:50.603 回答
-2

对于那里的所有大人物。这会帮助你

     synch.m
    ========

    #import "thenewapi.h"



    @interface thenewapi ()

    {

    NSData *data;

    NSMutableArray*mutarray;

    int index;

    NSString *s;

    NSMutableArray *arr;

    NSMutableArray *imgarr;



}



@end



@implementation thenewapi



- (void)viewDidLoad {

    [super viewDidLoad];

    index=0;

    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://ir.com/wecare/api/partnership/partnership_heading?format=json"]];

    NSURLResponse *response=nil;

    NSError *error=nil;

    data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    mutarray=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];



    arr=[mutarray valueForKey:@"0"];

       _idlbl.text=[arr valueForKey:@"id"];

    _titlelbl.text=[arr valueForKey:@"title"];

   _destxtvw.text=[arr valueForKey:@"description"];



    imgarr=[mutarray valueForKey:@"images"];



  s=[[imgarr objectAtIndex:index] valueForKey:@"image"];



    NSString *f=[NSString stringWithFormat:@"http://irtech.com/wecare/uploads/partnership/%@",s];



    NSURL *g=[[NSURL alloc]initWithString:f];



    data=[NSMutableData dataWithContentsOfURL:g];

    self.imgvw.image=[UIImage imageWithData:data];









    // Do any additional setup after loading the view.

}



- (IBAction)clickbtn:(id)sender

{

    ++index;

        s=[[imgarr objectAtIndex:index]valueForKey:@"image"];



        NSString *f=[NSString stringWithFormat:@"http://irdtech.com/wecare/uploads/partnership/%@",s];



        NSURL *g=[[NSURL alloc]initWithString:f];

        data=[NSMutableData dataWithContentsOfURL:g];

        self.imgvw.image=[UIImage imageWithData:data];



}

========================================================================================================




Asynch.h
========

#import <UIKit/UIKit.h>



@interface thenewAsynch : UIViewController<UITableViewDelegate,UITableViewDataSource,NSURLConnectionDataDelegate>

@property (strong, nonatomic) IBOutlet UIImageView *imgvw;

@property (strong, nonatomic) IBOutlet UITableView *tbl;

@property (strong, nonatomic) IBOutlet UIButton *click;







@end



Asynch.m
========


#import "thenewAsynch.h"



@interface thenewAsynch ()

{

    NSDictionary *dic;

    NSMutableArray *mutarray;

    NSMutableData *mutdata;

    NSString *s;

    NSArray *arr;

    NSArray *imgarr;

    NSData *data;

    int index;

}



@end



@implementation thenewAsynch



- (void)viewDidLoad {

    [super viewDidLoad];



    mutarray=[[NSMutableArray alloc]init];

    mutdata=[[NSMutableData alloc]init];

    dic=[[NSDictionary alloc]init];

    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://irtech.com/wecare/api/partnership/partnership_heading?format=json"]];

    NSURLConnection *connect=[NSURLConnection connectionWithRequest:request delegate:self];

    NSLog(@"Connection String=%@",connect);

    [self.view addSubview:_tbl];



    arr=[mutarray valueForKey:@"0"];



    imgarr=[mutarray valueForKey:@"images"];













    // Do any additional setup after loading the view.

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

{

    return arr.count;



}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

{

    static NSString *cellid=@"Cell Identifier";

    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellid];

    if(cell==nil)

    {

        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellid];

    }

    if(indexPath.row==0)

    {

        cell.textLabel.text=[arr valueForKey:@"id"];

    }

    else if (indexPath.row==1)

    {

        cell.textLabel.text=[arr valueForKey:@"title"];

    }

    else if (indexPath.row==2)

    {

        cell.textLabel.text=[arr valueForKey:@"subtitle"];





    }

    else if (indexPath.row==3)

    {

        cell.textLabel.text=[arr valueForKey:@"description"];





    }



    return cell;



}



//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

//{

//    return mutarray.count;

//}



- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response

{

    return request;

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{



}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    [mutdata appendData:data];

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    mutarray=[NSJSONSerialization JSONObjectWithData:mutdata options:NSJSONReadingMutableContainers error:nil];

    arr=[mutarray valueForKey:@"0"];



    imgarr=[mutarray valueForKey:@"images"];

    s=[[imgarr objectAtIndex:index]valueForKey:@"image"];



    NSString *f=[NSString stringWithFormat:@"http://irtech.com/wecare/uploads/partnership/%@",s];



    NSURL *g=[[NSURL alloc]initWithString:f];

    data=[NSMutableData dataWithContentsOfURL:g];

    self.imgvw.image=[UIImage imageWithData:data];

    [_tbl reloadData];

}



- (IBAction)clickclick:(id)sender



{ ++index;

    s=[[imgarr objectAtIndex:index]valueForKey:@"image"];



    NSString *f=[NSString stringWithFormat:@"http://irtech.com/wecare/uploads/partnership/%@",s];



    NSURL *g=[[NSURL alloc]initWithString:f];

    data=[NSMutableData dataWithContentsOfURL:g];

    self.imgvw.image=[UIImage imageWithData:data];



}
于 2018-06-23T15:30:06.563 回答