JSONModel returns nil

社会主义新天地 提交于 2019-12-04 04:53:52

问题


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 ?


回答1:


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


来源:https://stackoverflow.com/questions/18890762/jsonmodel-returns-nil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!