4

i have a problem in reading JSON by JSONModel library

{"images":[{"id":1,"name":"name1","img":"3423","note":"note1"},{"id":2,"name":"name2","img":"rew","note":"note2"},{"id":3,"name":"name3","img":"dsfs","note":"note3"},{"id":4,"name":"name4","img":"cxvxc","note":"note4"},{"id":5,"name":"name5","img":"erwe","note":"note5"}]}

the class model is

#import "JSONModel.h"

@protocol ImagesModel @end

@interface ImagesModel : JSONModel
@property int id;
@property (strong, nonatomic) NSString* name;
@property (strong, nonatomic) UIImage* img;
@property (strong, nonatomic) NSString* note;
@end

and i got this error

   Terminating app due to uncaught exception 'Bad property protocol declaration', reason: '<ImagesModel> is not allowed JSONModel property protocol, and not a JSONModel class.'

Any help please?

Marin Todorov
  • 6,377
  • 9
  • 45
  • 73
Tux Dawwas
  • 78
  • 1
  • 8

2 Answers2

4

I can see two problems with the code you pasted in.

Your model is good, but it is a model for one item - ie. it's the model you are going to use to load a single image - not all the images at once. Therefore you need a model to describe that you have a collection of images, and another model (the one you have) to describe each of the image objects.

The second problem is that one of your properties is a UIImage object, but you're passing string in your JSON feed.

Therefore to have your example working you need:

#import "JSONModel.h"

//define the single image object protocol
@protocol ImageModel @end

//define the single image model
@interface ImageModel : JSONModel
@property int id;
@property (strong, nonatomic) NSString* name;
@property (strong, nonatomic) NSString* img;
@property (strong, nonatomic) NSString* note;
@end

@implementation ImageModel
@end

//define the top-level model for the collection of images
@interface Images : JSONModel
@property (strong, nonatomic) NSArray<ImageModel>* images;
@end

And then read your JSON string and create an Images model:

NSError* err = nil;
Images* imagesCollection = [[Images alloc] initWithString:JSONstring error:&err];

Then each of the elements in imagesCollection.images will be an ImageModel instance.

Voila!

Marin Todorov
  • 6,377
  • 9
  • 45
  • 73
  • When we do "initWithDictionary" and the Json response has a Array of Dictionary, it returns a JSONModelError "Attempt to initialize JSONModel object using initWithDictionary:error: but the dictionary parameter was not an 'NSDictionary'" within the initWithDictionary Model. – Ansal Antony Aug 14 '15 at 13:52
0

I think you didn't implement this class in the .m file. So when JsonModel internally executes the NSClassFromString() method, it crashes.

Kaushik Makwana
  • 1,329
  • 2
  • 14
  • 24
  • From Review: Hi, this post does not seem to provide a [quality answer](https://stackoverflow.com/help/how-to-answer) to the question. Please either edit your answer and improve it, or just post it as a comment. – sɐunıɔןɐqɐp Jan 21 '19 at 09:39