I have a model using JSONModel in my objective c application. JSONModel github I am trying init my model from a response of server. The response of server is this:
[ { "id": 0, "name": "Jhon" }, { "id": 1, "name": "Mike" }, { "id": 2, "name": "Lua" } ]
My JSONModel is:
@protocol People @end
@interface People : JSONModel
@property (nonatomic, strong) NSArray <Person> * peopleArray;
@end
@protocol Person @end
@interface Person : JSONModel
@property (nonatomic, strong) NSNumber <Optional> * id;
@property (nonatomic, strong) NSString <Optional> * name;
@end
And I'm trying init this then get the response from server like:
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseData options:NSJSONWritingPrettyPrinted error:&error];
People *peoplemodel = [[People alloc] initWithData:jsonData error:&error];
But I'm getting a null model.
I think that the problem is the format response like
[{ }]
But I don't know how to convert this.
is possible init a JSONModel from an array of json objects?
How can I do this?
The library you reference appears to only be compatible with an NSDictionary root Json object, whereas you have an NSArray root json object.
https://github.com/jsonmodel/jsonmodel/blob/master/JSONModel/JSONModel/JSONModel.m#L123
https://github.com/jsonmodel/jsonmodel/blob/master/JSONModel/JSONModel/JSONModel.m#L161
If you check the error returned when attempting to initWithData, I'm sure it will have this error message:
Your currently server JSON response:
An example of what the JSON would look like that the JSONModel lib would be able to parse:
If you're unable to modify your server response on the backend to have it return an NSDictionary as the root JSON object, you could pre-process the returned data to format for what JSONModel lib is expecting (NSDictionary root).
Here's an example of what I mean (specifically you'll want to use something like
jsonDataUsingYourCurrentArrayStructureWithPreProcessing:to pre-process your JSON data:Alternatively, you can just roll your own initialization from the JSON array, something along these lines in the People Class: