JsonModel cannot convert an array in json to jsonmodel inherited class - ios

I have modeled my api result as following:
#import "PTPDestination.h"
#interface PTPIndex : PTPBaseEntity
#property (strong, nonatomic) NSNumber * citiesCount;
#property (strong, nonatomic) NSNumber * hotelsCount;
#property (strong, nonatomic) NSArray<PTPDestination *> * top_destinations;
#end
I also modeled PTPDestination like this:
#interface PTPDestination : PTPBaseEntity
#property (assign, nonatomic) NSNumber * id;
#property (assign, nonatomic) NSNumber * min_price;
#property (assign, nonatomic) NSNumber * max_discount;
#property (assign, nonatomic) NSString * title;
#end
And I call my api with AFNetworking like this:
AFHTTPSessionManager * manager = [self createAPISessionManager];
[manager GET:[self createServiceUrlWithMethod:#"someURL"] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSError * error = nil;
PTPIndex * index = [[PTPIndex alloc] initWithDictionary:responseObject error:&error];
if (error) {
callback (nil, [PTPApiCenteralizedErrorHandler getErrorFromApiError:error task:task responseObject:responseObject]);
return;
}
callback (index, nil);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
callback (nil, [PTPApiCenteralizedErrorHandler getErrorFromApiError:error task:task]);
}];
The problem is with array of destinations. I don't know why the array is not converted to PTPDestination object and it remains as an array of NSDictionaries.
Why this happens and how can I have an array of my custom class?

No, JSON Model Also Converted the Array to JSONObject, if you want to access the PTPDestination class properties.
PTPIndex class
#import "JSONModel.h"
#interface PTPIndex : JSONModel
#property (strong, nonatomic) NSNumber * citiesCount;
#property (strong, nonatomic) NSNumber * hotelsCount;
#property (strong, nonatomic) NSArray<PTPDestination *> * top_destinations;
#end
PPTPDestination class
#import "JSONModel.h"
#interface PTPDestination : JSONModel
#property (assign, nonatomic) NSNumber * id;
#property (assign, nonatomic) NSNumber * min_price;
#property (assign, nonatomic) NSNumber * max_discount;
#property (assign, nonatomic) NSString * title;
#end
NSDictionary "data" from the network Response
PTPIndex *ptpInd = [[PTPIndex alloc] initWithDictionary:data error:&error];
find the total number of PTPDestination and run in the loop.
You can access the object like this.
PTPDestination *ptpdest = [ptpInd PTPDestination[0]];

Related

Creating a data model from JSON

I have a JSON that looks like this :
{
"club": [
{
"titles": "1",
"league": "epl",
"country": "england",
}
}
And I have created a property like this :
#property (strong, nonatomic) NSMutableArray <Clubs> *club;
The club property inherits from the Clubs class which has the titles, leagues and country properties.
When I try to create a dictionary with that data model, I am unable to access the properties inside the club array.
Am I creating the data model incorrectly ?
Creating the dictionary:
for (NSDictionary *dictionary in responseObject) {
if (![self.searchText isEqualToString:#""]) {
self.predictiveProductsSearch = [[PerdictiveSearch alloc]initWithDictionary:dictionary error:nil];
self.predictiveTableView.dataSource = self;
[self.predictiveTableView reloadData];
self.predictiveTableView.hidden = NO;
}
}
Clubs class
#import <JSONModel/JSONModel.h>
#protocol Clubs #end
#interface Clubs : JSONModel
#property (strong, nonatomic) NSString <Optional> * titles;
#property (strong, nonatomic) NSString <Optional> * league;
#property (strong, nonatomic) NSString <Optional> * country;
#property (strong, nonatomic) NSString <Optional> * topGS;
#property (strong, nonatomic) NSString <Optional> * GoalSc;
#property (strong, nonatomic) NSString <Optional> * TransferBudget;
#end
Please use below code to achieve JSON Model saving:
_club = [[NSMutableArray alloc]init];
NSDictionary *responseObject = #{
#"club": #[
#{
#"titles": #"1",
#"league": #"epl",
#"country": #"england"
}]
};
NSArray *newResponseObject = [responseObject objectForKey:#"club"];
for (NSDictionary *dictionary in newResponseObject) {
Clubs *objClubs = [[Clubs alloc]initWithDictionary:dictionary error:nil];
[_club addObject:objClubs];
}
NSLog(#"%#",[_club objectAtIndex:0]);
which print like below :
<Clubs>
[titles]: 1
[country]: england
[GoalSc]: <nil>
[league]: epl
[topGS]: <nil>
[TransferBudget]: <nil>
</Clubs>

Delete Image Stored As Attribute of Core Data Entity

I have a core data entity called CollectedLeaf.
#interface CollectedLeaf : NSManagedObject <LeafletRecognitionRequestDelegate>
{
id <CollectedLeafDelegate> delegate_;
}
#property (nonatomic, assign) id <CollectedLeafDelegate> delegate;
#property (nonatomic, retain) NSString* leafID;
#property (nonatomic, retain) NSString* selectedSpecies;
#property (nonatomic, retain) NSString* latitude;
#property (nonatomic, retain) NSString* longitude;
#property (nonatomic, retain) NSString* altitude;
#property (nonatomic, retain) NSDate* collectedDate;
#property (nonatomic, retain) NSData * localImage;
#property (nonatomic, retain) LeafletURL* originalImageURL;
#property (nonatomic, retain) LeafletURL* segmentedImageURL;
#property (nonatomic, retain) Species* selectedSpeciesRel;
#property (nonatomic, retain) NSNumber* syncStatus;
#property (nonatomic, retain) NSDate* lastModified;
#property (nonatomic, retain) NSNumber* uploaded;
#property (nonatomic, retain) NSString* userDataset;
#property (nonatomic, retain) NSSet* CandidateSpecies;
When there isn't an internet connection, I convert the image taken with UIImagePickerController as NSData and store to my core data.
if (_internetReachability == NotReachable){
//Internet Connection Not Available
if(imageToUpload){
//They just tried to upload photo
self.originalImageView.image = [UIImage imageWithData:imageToUpload];
/*Save photo to core data here*/
NSManagedObjectContext* context = self.collectedLeaf.managedObjectContext;
collectedLeaf.localImage = imageToUpload;
NSError* error;
[context save:&error];
}
As soon as there is internet connection, I upload the image to the server. But I know that saving images locally takes up a lot of memory, so I would like to delete the local image (just the value assigned to the attribute, not the entire object). Could I erase the image with collectedLeaf.localImage = nil ?
You can erase the image by setting localImage to nil.
// Upload the image to server
collectedLeaf.localImage = nil;
NSError* error;
[context save:&error];

How can I store array values (RLMArray) in Realm DB with Objective C?

How can I store array values (RLMArray) in Realm DB ?
My .h file below,
#interface Hotlines : RLMObject
#property (strong, nonatomic) NSString *id;
#property (strong, nonatomic) NSString *department_name;
#property (strong, nonatomic) NSString *flag;
#property (strong,nonatomic) RLMArray<Numbers> *numbers;
#end
You need to create realm model for Numbers array:
#import <Realm/Realm.h>
// Define your models for Numbers array
#interface Numbers : RLMObject
#property NSInteger *num;
#property (strong, nonatomic) NSString *name;
#end
RLM_ARRAY_TYPE(Numbers) // define RLMArray< Numbers >
// Define your models for Numbers array
#interface Hotlines : RLMObject
#property (strong, nonatomic) NSString *id;
#property (strong, nonatomic) NSString *department_name;
#property (strong, nonatomic) NSString *flag;
#property (strong,nonatomic) RLMArray<Numbers> *numbers;
#end
// Implementations
#implementation Numbers
#end // none needed
#implementation Hotlines
#end // none needed
For more information refer Realm Objective c
Update :
RLMRealm *realm = [RLMRealm defaultRealm];
[realm transactionWithBlock:^{
Hotlines *obj = [[Hotlines alloc] init];
obj.department_name = #"anyString";
Numbers *number = [[Numbers alloc] init]
number.num = 1;
[obj.numbers addObject:number]
[realm addObject:obj];
}];
For multiple data :
[realm transactionWithBlock:^{
Hotlines *obj = [[Hotlines alloc] init];
obj.department_name = #"anyString";
for (int i=0; 1< 10; i++) {
Numbers *number = [[Numbers alloc] init]
number.num = i;
number.name = #"XYZ"
[obj.numbers addObject:number]
}
[realm addObject:obj];
}];
Can be done with primitives if you really just want numbers:
#interface Hotlines : RLMObject
#property NSString *id;
#property NSString *department_name;
#property NSString *flag;
#property RLMArray<NSNumber*><RLMFloat> *numbers;
#end
From the realm docs:
RLMArrays can store primitive values in lieu of Realm objects. In
order to do so, constrain a RLMArray with one of the following
protocols: RLMBool, RLMInt, RLMFloat, RLMDouble, RLMString, RLMData,
or RLMDate
.

iOS JSONModel json instance

I am attempting to use this JSONModel library in an app I'm building. I've been following this article, but for some reason I keep getting (null) when attempting to parse the json string. I was told that it is because I'm not creating a json instance; but it seems to me I am. Below is the code, can anyone see what I'm missing? I'm attempting to use this web service, with these inputs:
emailAddress: wufpakjack#yahoo.com;
password: test;
companyId: 2579;
scheduleDate: 20140415.
myShiftModel.h
#import "JSONModel.h"
#interface myShiftModel : JSONModel
#property (assign, nonatomic) NSString *shiftName;
#property (assign, nonatomic) NSString *shiftStartTime;
#property (assign, nonatomic) NSString *shiftPosition;
#end
dailyViewModel.h
#import "JSONModel.h"
#import "myShiftModel.h"
#protocol dailyViewModel #end
#interface dailyViewModel : JSONModel
#property (assign, nonatomic) int numAvailableXChanges;
#property (strong, nonatomic) NSString *todaysForecast;
#property (assign, nonatomic) int todaysTemperature;
#property (strong, nonatomic) myShiftModel *workShift;
#end
dailyFeed.h
#import "JSONModel.h"
#import "dailyViewModel.h"
#interface dailyFeed : JSONModel
#property (strong, nonatomic) NSArray <dailyViewModel> *workShifts;
#end
mainViewController.m
#import "mainViewController.h"
#import "JSONModelLib.h"
#import "JSONModel+networking.h"
#import "dailyFeed.h"
#interface mainViewController () {
dailyFeed *feed;
}
#end
#implementation mainViewController
- (void)viewDidAppear:(BOOL)animated {
NSString *email = [[NSString alloc]initWithFormat:#"wufpakjack#yahoo.com"];
NSString *pass = [[NSString alloc]initWithFormat:#"test"];
NSString *compID = [[NSString alloc]initWithFormat:#"2579"];
NSString *date = [[NSString alloc]initWithFormat:#"20140415"];
NSString *urlString = [NSString stringWithFormat:#"http://qa.shiftzen.com/ws/schedutils.asmx/GetDailyView?emailAddress=%#&password=%#&companyId=%#&scheduleDate=%#", email,pass,compID,date];
NSLog(#"%#", urlString);
[JSONHTTPClient getJSONFromURLWithString:urlString
completion:^(NSDictionary *json, JSONModelError *err) {
NSError* error = nil;
feed = [[dailyFeed alloc] initWithDictionary:json error:&error];
NSLog(#"shifts: %#", feed.workShifts);
}];
}
#end
Any guidance would be greatly appreciated.
Warmest regards,
DB

how to get a NSArray object using JSONModel

i have a problem in reading JSON by JSONModel library https://github.com/icanzilb/JSONModel
and use the KivaDemo at the JSonModel app,the json :
"loans": [
{
"id": 547665,
"name": "Veronica",
"description": {
"languages": [
"en"
]
},
"status": "fundraising",
"funded_amount": 0,
i want to get the "en" ,
#interface KivaFeed : JSONModel
#property (strong, nonatomic) NSArray<LoanModel, ConvertOnDemand>* loans;
#property (strong, nonatomic) Paging *paging;
#end
#protocol LoanModel #end
#interface LoanModel : JSONModel
#property (strong, nonatomic) NSString* name;
#property (strong, nonatomic) NSString* status;
#property (strong, nonatomic) NSString* use;
#property (strong, nonatomic) NSString* id;
#property (strong, nonatomic) NSString* funded_amount;
#property (strong, nonatomic) LocationModel* location;
#property (strong, nonatomic) Image* image;
#property (strong, nonatomic) Description* description;
#end
#interface Description : JSONModel
#property (strong, nonatomic) NSArray<Languages, ConvertOnDemand>* languages;
#end
#protocol Languages #end
#interface Languages : JSONModel
#end
kiva = [[KivaFeed alloc] initFromURLWithString:#"http://api.kivaws.org/v1/loans/search.json?status=fundraising"
completion:^(JSONModel *model, JSONModelError *e) {
[table reloadData];
NSLog(#"kiva.paging.page:%#",kiva.paging.page);
if (e) {
[[NSAlert alertWithError:e] beginSheetModalForWindow:self.view.window modalDelegate:nil didEndSelector:nil contextInfo:nil];
}
[self setLoaderVisible:NO];
}];
LoanModel* loan = kiva.loans[row];
NSString* message = [NSString stringWithFormat:#"%# from %#(%#) needs a loan %#",
loan.name, loan.location.country, loan.location.countryCode, loan.use
];
NSLog(#"loan:%#",loan.id);
NSLog(#"loan:%#",loan.funded_amount);
NSLog(#"loan.image.id:%#",loan.image.id);
NSLog(#"loan.description.languages:%#",loan.description.languages[0]);
last it give me 2013-04-15 13:16:09.163 JSONModelDemo_OSX[2308:303] loan.description.languages:(null). how to get the en,what mistake at my code?
modify as :
#interface Description : JSONModel
#property (strong, nonatomic) NSArray* languages;
#end
all is ok

Resources