【问题标题】:JSON Parsing in Objective-CObjective-C 中的 JSON 解析
【发布时间】:2013-06-06 05:17:05
【问题描述】:

我已经完成了有关 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

【问题讨论】:

  • 尝试记录错误:NSLog(@"Error: %@", [error localDescription])
  • @nic 请在问题本身中包含您的 JSON。问题应该是独立的,链接往往会在一段时间后停止工作。
  • json 有问题!
  • 您确定responseData 不是nil 或者至少是您希望从服务器返回的内容吗?
  • @bl 当时不是。

标签: iphone ios objective-c json


【解决方案1】:

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

     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];



}

【讨论】:

    【解决方案2】:

    你做错了。您已在字典(名为 json)中正确填写了 JSON 数据。但是你的 Main Dictionary 中有一个 Array of Dictionaries(称为 Albumvideo),titre 的值在 Albumvideo 数组中。

    正确的代码是:

    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 解析有一些正确的认识。

    【讨论】:

    • +1。很好的解释,而且完全正确(与其他解释不同)
    • 听起来很棒 :-) 如果我在其他数组中(在我的 JSON 中)有数组,这是否是相同的过程?我为我的“titre”做了这个:NSArray *titre = [albumsvi​​deo valueForKey:@"titre"];
    • @NicolasWilhem :理解这个概念。这取决于您在 JSON 中的内容。如果它是一个数组,那么你必须保存在 NSArray 中,如果它是一个字典,那么保存为 NSDictionary,如果你有字符串、整数、双精度等单个值,那么你必须使用适当的 Objective-C 数据类型来保存它们。
    • 谢谢你们,和你们一起学习比阅读大量不完整的教程更快更好。我现在有了一个很好的起点。
    • @NicolasWilhem:不要编辑问题。你应该问一个新的。
    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多