简体   繁体   English

Objective-C中的JSON解析

[英]JSON Parsing in Objective-C

I've done the Raywenderlich tutorial about JSON in iOS but I got difficulties to adapt it to my own JSON file. 我已经完成了有关iOS中JSON的Raywenderlich教程,但是我很难将其调整为适合自己的JSON文件。 Here is my JSON : 这是我的JSON

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

Here is my Code : 这是我的代码

- (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);
}

Log returns null . 日志返回null

You are doing it wrong. 你做错了。 You have filled your JSON Data in your Dictionary (named json ) correctly. 您已正确将JSON数据填充到字典(名为json )中。 But then you have an Array of Dictionaries (called Albumvideo ) inside your Main Dictionary and value of titre is inside Albumvideo Array. 但是然后您在主Dictionary就有了一个Array of Dictionaries (称为Albumvideo ), titre值在Albumvideo Array中。

The Correct Code is : 正确的代码是:

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

Understand the Concept. 了解概念。 It depends on what you have inside your JSON . 这取决于JSON If it's an Array ( Values inside [ ] ) then you have to save in NSArray , if it's a Dictionary ( Values inside { } ) then save as NSDictionary and if you have single values like string , integer, double then you have to save them using appropriate Objective-C Data types. 如果它是一个数组( [ ]内的值),则必须保存在NSArray ;如果它是一个字典( { }内的值), NSDictionary另存为NSDictionary ;如果您有单个值,如string,integer,double,则必须保存它们使用适当的Objective-C数据类型。

Hope, you got some proper idea about JSON Parsing . 希望您对JSON解析有一些正确的想法。

Answered by Vin is right. Vin的回答是正确的。 Basically, to parse json response look at the kind of bracket used. 基本上,要解析json响应,请查看所使用的括号类型。

Start parsing with the outer symbol and check for the symbol. 开始分析外部符号并检查符号。 If it is, 如果是,
1) { then it is NSDictionary. 1) {则为NSDictionary。
2) [ then it is NSArray. 2) [然后是NSArray。

These simple rules will make your life easy. 这些简单的规则将使您的生活变得轻松。 :) :)

For all the bigginers out there. 对于所有在那里的bigginers。 this will help you 这会帮助你

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



}

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

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