2015-09-25 2 views
-1

я стараюсь хранить JSON как этот учебникJSONModel - не может назначить сгружен JSON для моделирования как учебник

http://www.touch-code-magazine.com/how-to-fetch-and-parse-json-by-using-data-models/

В учебнике это объявить LocationModel в LoanModel.h.

@property (strong, nonatomic) LocationModel* location; 

Какие отлично работают в projectDemo, но когда я пытаюсь использовать его в моем проекте, как этот

@property(strong,nonatomic) ContentDetailModel *content; 

Она возвращает нуль.

Будет работать после того, как я удалю эту строку.

Вы можете проверить мой код, чтобы узнать, где это неправильно?

Вот данные JSON, что я пытаюсь принести

{ 

"status": "success", 

"content": [ 
    { 
     "id": 11447, 
     "title": "Arsenal's Afobe targets a full season on loan", 
     "dateTime": "30.10.2014 06:38", 
     "tags": [], 
     "content": [ 
      { 
       "type": "text", 
       "subject": "Benik Afobe", 
       "description": "The 21-year-old was last capped by the Three Lions in February 2013 when he featured for the Under-21s against Sweden at Walsall in a 4-0 win.\r\n\r\nA series of injuries since then have restricted his progress both on the club and international front and he spent the second half of last season on loan at Sheffield Wednesday." 
      } 
     ], 
     "ingress": "Arsenal and England Under-21s striker Afobe is hoping a full season on loan can help to rejuvenate his career.\r\n", 
     "image": "http://87.251.89.41/sites/default/files/afobe-celeb-dier.jpg", 
     "created": 1407476424, 
     "changed": 1414664497 
    } 
    ] 
} 

Вот моя модель в ContentListModel.h

@protocol ContentListModel 

@end 

@interface ContentListModel : JSONModel 

@property (assign,nonatomic) NSString * id; 
@property (strong,nonatomic) NSString * title; 
@property (strong,nonatomic) NSString * dateTime; 
@property (strong,nonatomic) NSArray * tags; 
@property (strong,nonatomic) NSString * ingress; 
@property (strong,nonatomic) NSString * image; 
@property (strong,nonatomic) NSString * created; 
@property (strong,nonatomic) NSString *changed; 

@property(strong,nonatomic) ContentDetailModel *content; 

@end 

Вот моя модель в ContentDetailModel.h

@interface ContentDetailModel : JSONModel 

@property(strong,nonatomic) NSString * type; 
@property(strong,nonatomic) NSString * subject; 
@property(strong,nonatomic)NSString * description; 

@end 

Вот FOTTFeed.h

#import <Foundation/Foundation.h> 
#import "JSONModel.h" 
#import "ContentListModel.h" 

@interface FOTTFeed : JSONModel 

@property (strong , nonatomic) NSArray<ContentListModel> *content; 

@end 

Вот мой код

#import "FeedList.h" 
#import "SWRevealViewController.h" 
#import "UIImageView+WebCache.h" 
#import "JSONModelLib.h" 
#import "FOTTFeed.h" 
#import "HUD.h" 
#import "FeedDetail.h" 

@interface FeedList(){ 
    FOTTFeed *feed; 
} 

@end 

@implementation FeedList{ 
    NSArray *tableData; 

} 
@synthesize tableView; 
@synthesize detailView; 

- (void)viewDidLoad { 
    [super viewDidLoad]; 



    _menu.target = self.revealViewController; 
    _menu.action = @selector(revealToggle:); 
    [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer]; 

    //background image 
    UIImage * background = [UIImage imageNamed:@"background_2.jpg"]; 
    UIImageView * imageView = [[UIImageView alloc]initWithImage:background]; 
    [self.tableView setBackgroundView:imageView]; 




    //set navigation bar colour 
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:(29/255.0) green:(43/255.0) blue:(58/255.0) alpha:1.0]]; 

} 


-(void)viewDidAppear:(BOOL)animated{ 

    [HUD showUIBlockingIndicatorWithText:@"Loading..."]; 

    //fetch the feed 
    feed = [[FOTTFeed alloc]initFromURLWithString:@"http://87.251.89.41/application/11424/article/get_articles_list" completion:^(JSONModel * model, JSONModelError *err){ 



     //hide the loader view 
     [HUD hideUIBlockingIndicator]; 

     //json fetch 
     NSLog(@"Content:%@",feed.content); 

     [self.tableView reloadData]; 

    }]; 

} 

-(void)viewWillAppear:(BOOL)animated{ 



    [super viewWillAppear:animated]; 
    [self.tableView reloadData]; 
} 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
    return [feed.content count]; 
} 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    // Configure the cell... 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    cell.tag = indexPath.row; 
    [cell setOpaque:NO]; 
    [cell setBackgroundColor: [UIColor clearColor]]; 


    ContentListModel *data = [feed.content objectAtIndex:indexPath.row]; 

    UIImageView *thumbnailImageView = (UIImageView *)[cell viewWithTag:100]; 
    UILabel *titleNews = (UILabel *)[cell viewWithTag:200]; 
    UILabel *Time = (UILabel *)[cell viewWithTag:300]; 
    UITextView * ingress = (UITextView *)[cell viewWithTag:400]; 

    ingress.editable = false; 

    titleNews.text = data.title; 


    ingress.text = data.ingress; 


    Time.text = data.dateTime; 



    [thumbnailImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", data.image]] placeholderImage:[UIImage imageNamed:@"dot.png"]]; 


    return cell; 

} 

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ 
    if([segue.identifier isEqualToString:@"showFeedDetail"]){ 
     NSIndexPath *indexpath = [self.tableView indexPathForSelectedRow]; 
     FeedDetail *detailView = segue.destinationViewController; 
     detailView.data = [feed.content objectAtIndex:indexpath.row]; 


    } 
} 

@end 
+0

Вы не разместили никакого действительного кода, просто некоторые объявления интерфейса. – rmaddy

+0

@rmaddy благодарит за ответ. Я уже редактирую свой пост. –

+0

Если вы не указали часть импорта. Где код, который обрабатывает JSON, и где код, который должен установить свойство 'content'? – rmaddy

ответ

1

JSON Detail массив:

"content": [ 
     { 
      "type": "text", 
      "subject": "Benik Afobe", 
      "description": "The 21-year-old was last capped by the Three Lions in February 2013 when he featured for the Under-21s against Sweden at Walsall in a 4-0 win.\r\n\r\nA series of injuries since then have restricted his progress both on the club and international front and he spent the second half of last season on loan at Sheffield Wednesday." 
     } 
    ] 

В модели ContentListModel, свойство "содержание", я думаю, Шоуда быть NSArray.

+0

Спасибо за ответ! это решило проблему. –

0

BWJSONMatcher - это легкая библиотека, которая поможет вам легко сопоставить строку JSON или объект JSON с вашей моделью данных. Если все свойства ваших моделей данных согласуются с ключами в данных json, BWJSONMatcher автоматически сопоставит их.

Подробные примеры here.