how to get a NSArray object using JSONModel - ios

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

Related

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
.

JsonModel cannot convert an array in json to jsonmodel inherited class

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

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

Can't map relationship into array in restkit

So, I have this result from the service:
{
"CustomerPromotions": [
{
"BottomTitle": "Thank you",
"IconURL": "",
"MiddleText": "399$",
"PromotionID": "123B456",
"SortOrder": 0,
"TopTitle": "Welcome to"
}
],
"CustomerStatus": 1,
"CustomerVoucherIcon": "",
"CustomerVoucherText": "",
"CustomerVoucherTitle": "",
"ErrorID": 0,
"ErrorMessage": "",
"FeedbackIndicator": false,
"FeedbackLowerText": "",
"FeedbackTitle": "",
"HPTopTitle": "Hello world",
"LocalCurrencySign": "$",
"LocalCurrencyValue": "3.30",
"LocalTime": "20:30",
"LocalWeather": "-5",
"PopUpTopTitle": ""
}
But for some reason I can't map CustomerPromotions it into an array, this is how my 2 objects looks like:
This is CustomerLogin.h:
#interface CustomerLogin : NSObject
#property (nonatomic) NSArray *customerPromotions;
#property (strong, nonatomic) NSNumber *customerStatus;
#property (strong, nonatomic) NSString *customerVoucherIcon;
#property (strong, nonatomic) NSString *customerVoucherText;
#property (strong, nonatomic) NSString *customerVoucherTitle;
#property (strong, nonatomic) NSNumber *errorID;
#property (strong, nonatomic) NSString *errorMessage;
#property (strong, nonatomic) NSNumber *feedbackIndicator;
#property (strong, nonatomic) NSString *feedbackLowerText;
#property (strong, nonatomic) NSString *feedbackTitle;
#property (strong, nonatomic) NSString *hpTopTitle;
#property (strong, nonatomic) NSString *localCurrencySign;
#property (strong, nonatomic) NSString *localCurrencyValue;
#property (strong, nonatomic) NSString *localTime;
#property (strong, nonatomic) NSString *localWeather;
#property (strong, nonatomic) NSString *popUpTopTitle;
#end
This is 'CustomerPromotions`:
#interface CustomerPromotions : NSObject
#property (strong, nonatomic) NSString *bottomTitle;
#property (strong, nonatomic) NSString *iconURL;
#property (strong, nonatomic) NSString *middleText;
#property (strong, nonatomic) NSString *promotionID;
#property (strong, nonatomic) NSNumber *sortOrder;
#property (strong, nonatomic) NSString *topTitle;
#end
This is the mapping:
RKObjectMapping *customerLoginMapping = [RKObjectMapping mappingForClass:[CustomerLogin class]];
[customerLoginMapping addAttributeMappingsFromDictionary:#{ #"CustomerStatus" : #"customerStatus",
#"CustomerVoucherIcon" : #"customerVoucherIcon",
#"CustomerVoucherText" : #"customerVoucherText",
#"CustomerVoucherTitle" : #"customerVoucherTitle",
#"ErrorID" : #"errorID",
#"ErrorMessage" : #"errorMessage",
#"FeedbackIndicator" : #"feedbackIndicator",
#"FeedbackLowerText" : #"feedbackLowerText",
#"FeedbackTitle" : #"feedbackTitle",
#"HPTopTitle" : #"hpTopTitle",
#"LocalCurrencySign" : #"localCurrencySign",
#"LocalCurrencyValue" : #"localCurrencyValue",
#"LocalTime" : #"localTime",
#"LocalWeather" : #"localWeather",
#"PopUpTopTitle" : #"popUpTopTitle" }];
RKObjectMapping *customerPromotionsMapping = [RKObjectMapping mappingForClass:[CustomerPromotions class]];
[customerPromotionsMapping addAttributeMappingsFromDictionary:#{ #"BottomTitle" : #"bottomTitle",
#"IconURL" : #"iconURL",
#"MiddleText" : #"middleText",
#"PromotionID" : #"promotionID",
#"SortOrder" : #"sortOrder",
#"TopTitle" : #"topTitle" }];
[customerLoginMapping addRelationshipMappingWithSourceKeyPath:#"customerPromotions" mapping:customerPromotionsMapping];
[[RKObjectManager sharedManager] addResponseDescriptor:[RKResponseDescriptor responseDescriptorWithMapping:customerLoginMapping
method:RKRequestMethodPOST
pathPattern:#"CustomerLogin"
keyPath:nil
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]];
This is the POST request:
NSDictionary *params = #{ #"AppID" : #"1",
#"AppPassword" : #"String content",
#"Password" : #"password",
#"UserName" : #"username" };
[[RKObjectManager sharedManager] postObject:[[CustomerLogin alloc] init]
path:#"CustomerLogin"
parameters:params
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(#"%#", operation.HTTPRequestOperation.responseString);
NSLog(#"%#", mappingResult.array);
CustomerLogin *customer = [mappingResult.array lastObject];
NSLog(#"%#", customer.customerPromotions);
NSLog(#"%#", customer.hpTopTitle);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"%#", error.localizedDescription);
}];
It just looks like your key name is wrong. You use a source key only, which means the source and destination should match but they don't actually match. Try:
RKRelationshipMapping *relationMapping = [RKRelationshipMapping relationshipMappingFromKeyPath:#"CustomerPromotions" toKeyPath:#"customerPromotions" withMapping:customerPromotionsMapping];
[customerLoginMapping addPropertyMapping:relationMapping];

Nested Array mapping restkit v.20

i wanna to map object in Google Places Api Photos
"photos" : [
{
"height" : 1224,
"html_attributions" : [
"\u003ca href=\"https://plus.google.com/105663944571530352563\"\u003eJoshua Gilmore\u003c/a\u003e"
],
"photo_reference" : "CnRoAAAAzuH4E1LVJHMdXNYbewoxcPE-qHizCE6pmOGjckeaCTKSL7xGVzLuwGxu7kx44bCWIZinMx4jkd8eenALB7w7jNRFrzE3hip2ld7096SI9D4sE2WpXQ1QH-iTQm7qhx4i6QSGGeXKjA9SfT4N6krwzRIQr1mulgyuKHP-2s_TJWIahhoUgxfccds3VAH2bj_CIQYzbAQZRhc",
"width" : 1632
}
],
i try with this code but photos is still nil
Place Class
#interface Place : NSObject
#property (nonatomic,strong) Geometry * geometry;
#property (nonatomic,strong) NSString * icon;
#property (nonatomic,strong) NSString * placeID;
#property (nonatomic,strong) NSString * name;
#property (nonatomic,strong) OpeningHours * opening_hours;
#property (nonatomic,strong) NSString * price_level;
#property (nonatomic,strong) NSString * rating;
#property (nonatomic,strong) NSString * vicinity;
#property (nonatomic,strong) NSArray *photos;
#property (nonatomic,strong) NSString *reference;
#end
Photos Class
#import <Foundation/Foundation.h>
#interface Photos : NSObject
#property (nonatomic,strong) NSNumber *height;
#property (nonatomic,strong) NSString *html_attributions;
#property (nonatomic,strong) NSString *photo_reference;
#property (nonatomic,strong) NSNumber *width;
#end
And i map with:
RKObjectMapping *placeMapping = [RKObjectMapping mappingForClass:[Place class]];
[placeMapping addAttributeMappingsFromDictionary:#{
#"icon" : #"icon",
#"id" : #"placeID",
#"name" : #"name",
#"reference" : #"reference",
#"price_level" : #"price_level",
#"rating" : #"rating",
#"vicinity" : #"vicinity",
}];
RKObjectMapping* photosMapping = [RKObjectMapping mappingForClass:[Photos class]];
[photosMapping addAttributeMappingsFromArray:#[#"height",#"photo_reference",#"html_attributions",#"width"]];
[placeMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"photos"
toKeyPath:#"photos"
withMapping:photosMapping]];
I don't know how to map photos as array in Place Class .
Any one can help me ?

Resources