Question

I'mm using JSONModel to get the JSON from the URL. It's a very simple object, containing only 2 strings - "name" and "url".

First I made the Object Model:

@protocol
Tutorial
@end
@interface Tutorial : JSONModel
@property (nonatomic, strong)   NSString *name;
@property (nonatomic, strong)   NSString *url;
@end

Then Object Feed:

#import "JSONModel.h"
#import "Tutorial.h"
@interface TutorialFeed : JSONModel
@property (nonatomic, strong)   NSArray <Tutorial> *tutorials;
@end

and then in MasterViewController.m:

#import "MasterViewController.h"
#import "DetailViewController.h"
#import "TutorialFeed.h"
#import "JSONModelLib.h"

@interface MasterViewController () {
  TutorialFeed *feed;
  TutorialFeed *testFeed;
}
@end
@implementation MasterViewController
-(void)viewDidAppear:(BOOL)animated
{
    feed = [[TutorialFeed alloc]

initFromURLWithString:@"http://api.matematikfessor.dk/apps/teacher_videos"
       completion:^(JSONModel *model, JSONModelError *err) {
           NSLog(@"Tutorials %@", feed.tutorials);
       }];
 }
 @end

The problem is, I get returned nil in my log :( Im not sure why is this happening, because I managed to fetch data from JSON from this URL: Kiwa URL

All that done, following this tutorial

Im not sure what am I doing wrong. Does anybody has any clue ?

Était-ce utile?

La solution

Explanation:

First of all JSONModel expects your JSON top object to be a dictionary, only that way it can match its keys to a model's properties.

Your model called TutorialFeed expects to be fed JSON matching the property name "tutorials".This means your JSON feed must be in the form:

{ "tutorials": [{obj1}, {obj2}, {obj3}, ...] }

What you have in fact at: http://api.matematikfessor.dk/apps/teacher_videos is

[{obj1}, {obj2}, {obj3}]

That's why your model instance is in fact "nil" because the JSON structure didn't match what your model expects.

Solution:

If you have an array at the top of your JSON feed (like the one on the URL you use) you have two options:

1) introduce a new key in your JSON feed - i.e. alter the JSON to be in the form of {"tutorials": [obj1, obj2, etc...]}

2) You can use another method to parse the JSON feed. Look up the docs here and use the static method that parses a list of objects:

#import "JSONModel+networking.h"
...
[JSONHTTPClient   
  getJSONFromURLWithString:@"http://api.matematikfessor.dk/apps/teacher_videos"
  completion:^(id feed, JSONModelError *err) {
    NSArray* tutorials = [Tutorial arrayOfModelsFromDictionaries: feed];
    NSLog(@"tutorials: %@", tutorials);
  }];
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top