I have the following Mantle object & want to convert the dictionary to Mantle object. but the conversion always returns empty MTLModel object.
Any ideas?
//ABC.h
#interface ABC : MTLModel<MTLJSONSerializing>
#property (nonatomic, strong) NSString *Identifier;
#property (nonatomic, strong) NSString *Name;
#property (nonatomic, strong) NSString *ImageURLString;
#property (nonatomic, strong) NSString *Desc;
#property (nonatomic, strong) NSString *lastUpdated;
#end
// ABC.m
#implementation ABC
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return #{
#"Identifier" : #"id",
#"Name" : #"name",
#"Desc" : #"desc",
#"ImageURLString" : #"image_url",
#"lastUpdated" : #"last_updated_at"
};
}
#end
Calling code:
ABC *abc = [MTLJSONAdapter modelOfClass:ABC.class fromJSONDictionary:tempDict error:NULL];
The JSON dictionary is:
{
desc = "asdadasdakjqewqwmsdnasdaksdasd";
id = adsasdasdasdasd;
"image_url" = "http://upload.wikimedia.org/wikipedia/commons/thumb/1/19/abc.JPG";
"last_updated_at" = "2015-07-25 04:22:39.851710";
name = asdasdqwe;
}
The result ABC object has no contents. Can't figure what I am missing here.
Any ideas???
Try with this snippet and debug the adapterError. May have relevant information about the conversion from NSDictionary to Mantle object
//Create Mantle object from NSDictionary using MTLJSONSerialization
NSError *adapterError;
MTLModel *user = [MTLJSONAdapter modelOfClass:MTLModel.class fromJSONDictionary:dictionary error:&adapterError];
if(adapterError) {
PrintError(adapterError)
return nil;
}
id = adsasdasdasdasd;
needs to be
id = "adsasdasdasdasd";
Related
Well this is bizarre and I can't find any explanation.
The issue is that I am "transforming" a object property to a value into a NSDictionary and in a specific value it "encodes" a "special character" but on other values it doesn't.
This is the .h file for the object where I declare the properties:
#import <CoreLocation/CoreLocation.h>
#import "ModelObject.h"
#interface CheckinObject : ModelObject
#property (nonatomic,strong) NSString *name;
#property (nonatomic,strong) NSString *num;
#property (nonatomic,strong) NSString *date;
This is the .m file, where I synthesize and put it into a NSDictionary:
#implementation CheckinObject
#synthesize name;
#synthesize num;
#synthesize date;
//bunch of other uninteresting code
- (NSDictionary*)toDictionary {
NSLog(#"=> self.num : %#", self.num);
NSDictionary *dic = #{
#"date" :self.date,
#"name" :self.name,
#"num" :self.num
};
NSLog(#"=> dic.num : %#", dic[#"num"]);
NSLog(#"=> dic : %#", dic);
return dic;
}
This is the output:
2016-05-25 21:03:44.333 FoodTruckApp[1320:614394] => self.num : 23–187
2016-05-25 21:03:44.334 FoodTruckApp[1320:614394] => dic.num : 23–187
2016-05-25 21:03:44.335 FoodTruckApp[1320:614394] => dic : {
date = "2016-05-25 21:03:44";
name = "Alameda dos Carvalhos";
num = "23\U2013187";
}
Any thought on what I might be missing here?
Cheers.
Object returns nil description after alloc and init..can any one tell me i have to display the data which comes from server...when i clicks on edit button it goes to shoow room class in that class.. inside textfields hav to display the information .can any one help me
#interface HeadOfficeDetails : NSObject
#property(nonatomic,strong) NSMutableArray *ofcContact;
#property(nonatomic,strong) OfficeDocument *ofcDocument;
#property(nonatomic,strong) OfficePrice *ofcPrice;
#property(nonatomic,strong) CityClass *city;
#property(nonatomic,strong) StateClass *state;
#property(nonatomic,strong) DistrictClass *district;
#property(nonatomic,strong)NSString *shrtname;
#property(nonatomic,strong)NSString *shwrmname;
#property(nonatomic,strong)NSString *shop;
#property(nonatomic,strong)NSString *door;
#property(nonatomic,strong)NSString *buildng;
#property(nonatomic,strong)NSString *flr;
#property(nonatomic,strong)NSString *tele;
#property(nonatomic,strong)NSString *pin;
#property(nonatomic,strong)NSString *main;
#property(nonatomic,strong)NSString *dist;
#property(nonatomic,strong)NSString *designan;
#property(nonatomic,strong)NSString *depart;
#property(nonatomic,strong)NSString *emai;
#property(nonatomic,strong)NSString *mobile;
#property(nonatomic,strong)NSString *strt;
#property(nonatomic,strong)NSString *area;
#property(nonatomic,strong) NSString *jwleryname;
#property(nonatomic,strong) NSString *officeid;
-(void)setAttributes:(NSDictionary *)attributes;
///////////////////////////////////////////////
showroom class
headdetails=[[HeadOfficeDetails alloc]init];
self.txtshowroom.text=headdetails.jwleryname;
NSLog(#"%# :",self.txtshowroom.text);
NSNumber *officeid=headdetails.officeid;
NSLog([NSString stringWithFormat:#"%#",officeid]);
[self.txtshortname setText:headdetails.jwleryname];
[self.txtshowroom setText:headdetails.shwrmname];
[self.txtstreet setText:headdetails.strt];
[self.txtarea setText:headdetails.area];
[self.txtmain setText:headdetails.main];
[self.txtbuilding setText:headdetails.buildng];
[self.txtname setText:self.cntctcls.contactname];
[self.txtdesign setText:self.cntctcls.desig];
[self.txtdepartmnt setText:self.cntctcls.depart];
[self.txtmbl setText:self.cntctcls.mobile];
[self.txtemail setText:self.cntctcls.email];
[self.txtfloor setText:headdetails.flr];
[self.txttel setText:headdetails.tele];
[self.txtpincode setText:headdetails.pin];
[self.txtshop setText:headdetails.shop];
Here are i put example code for show NSObject class data that save during data fetch from server and show on another class by using its instance.
Following is create a NSObject class for storing FBLogin userDetauls:
#import <Foundation/Foundation.h>
#interface FBUser : NSObject
#property (nonatomic,strong) NSString *FBUserId;
#property (nonatomic,strong) NSString *FBUserName;
#property (nonatomic,strong) NSString *FBUserFirstName;
#property (nonatomic,strong) NSString *FBUserLasttName;
#property (nonatomic,strong) NSString *FBUserEmail;
#property (nonatomic,strong) NSString *FBUserBio;
#property (nonatomic,strong) NSString *FBUserLocation;
+(instancetype)SharedFBUser;
-(void)ClearFBuser;
+(NSString*)CheckEmtryElseAlert:(NSString*)strValue;
#end
Following is an Implementation class here we create SharedFBUser that allcate FBUser object once if that found nil so when no need to do code alloc init during show time
#import "FBUser.h"
static FBUser* fbObject;
#implementation FBUser
+(instancetype)SharedFBUser
{
if(fbObject == nil)
{
fbObject =[[FBUser alloc]init];
}
return fbObject;
}
-(void)ClearFBuser
{
fbObject = nil;
self.FBUserId = nil;
self.FBUserName = nil;
self.FBUserFirstName =nil;
self.FBUserLasttName = nil;
self.FBUserEmail = nil;
self.FBUserBio = nil;
self.FBUserLocation = nil;
}
Now following code for how to use FBUser class for save data .H class:
#import <UIKit/UIKit.h>
#import "FBUser.h"
#interface LoginViewController : UIViewController
#property(nonatomic,strong)FBUser *fbObject;
#end
And you can save data in FBCallback:
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"id, name, link, first_name, last_name, picture.type(large), email, birthday, bio ,location ,friends ,hometown , friendlists"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error)
{
NSLog(#"resultis:%#",result);
[FBUser SharedFBUser].FBUserId =[result valueForKey:#"id"];
[FBUser SharedFBUser].FBUserEmail =[result valueForKey:#"email"];
[FBUser SharedFBUser].FBUserName =[result valueForKey:#"name"];
[FBUser SharedFBUser].FBUserFirstName =[result valueForKey:#"first_name"];
[FBUser SharedFBUser].FBUserLasttName =[result valueForKey:#"last_name"];
}
else
{
NSLog(#"Error %#",error);
}
}];
And following code for show the data that have stored in FBuser class
#import "FBUser.h"
self.lblEmail.text = [FBUser SharedFBUser].FBUserEmail;
self.lblusename.text = [FBUser SharedFBUser].FBUserName;
self.lblfirstname.text = [FBUser SharedFBUser].FBUserFirstName;
self.lbllastname.text = [FBUser SharedFBUser].FBUserLasttName;
Hope that help this fully description about use and create. this is my working code.
Not sure what are you doing, may you need something like parse dictionary to object first.
headdetails=[[HeadOfficeDetails alloc]init];
New Object created so all properties will nil.
you need assign value for it like
headdetails=[[HeadOfficeDetails alloc]initWithDictionary:attributes];
You can parse it your self or looking some 3rd library like:JSonModel
I have a slightly complex nested JSON object that I need to map to Objective-C class. One think I need to do is skip levels in JSON when mapping. Here is what I mean:
I want to map the following JSON Dictionary:
NSDictionary *JSONDictionary = #{
#"status" : #"PASSWORD_EXPIRED",
#"_embedded" : #{
#"user" : #{
#"id" : #"00ub0oNGTSWTBKOLGLNR",
#"profile" : #{
#"login" : #"isaac#example.org",
#"firstName" : #"Isaac",
#"lastName" : #"Brock",
#"locale" : #"en_US",
#"timeZone" : #"America/Los_Angeles"
}
}
}
};
to
#interface Authentication : MTLModel <MTLJSONSerializing>
#property (strong, nonatomic) NSDate* expiresAt;
#property (strong, nonatomic) NSString* status;
#property (strong, nonatomic) NSString* relayState;
#property (strong, nonatomic) NSString* sessionToken;
#property (strong, nonatomic) NSString* stateToken;
//Embeded Resources
#property (strong, nonatomic) User* user;
#end
As you can see I am not creating an object for "_embeded". I am skipping it and mapping user to a User object.
Can this be achieved? If so How?
I have tried this in the implementation but it did not work:
#implementation Authentication
+ (NSDictionary*)JSONKeyPathsByPropertyKey {
return #{
#"expiresAt" : #"expiresAt",
#"status" : #"status",
#"sessionToken" : #"sessionToken",
#"stateToken" : #"stateToken",
#"relayState" : #"relayState",
#"user" : #"_embeded/user",
};
}
+ (NSValueTransformer *)userJSONTransformer {
return [NSValueTransformer mtl_JSONDictionaryTransformerWithModelClass:User.class];
}
#end
I used to do it with the following code:
+ (NSValueTransformer *)userJSONTransformer {
return [MTLValueTransformer reversibleTransformerWithForwardBlock:^id(NSDictionary *userDict) {
return [MTLJSONAdapter modelOfClass:[User class] fromJSONDictionary:userDict error:nil];
} reverseBlock:^id(User *user) {
return [MTLJSONAdapter JSONDictionaryFromModel:user];
}];
}
And also in +JSONKeyPathsByPropertyKey I think it should be #"user" : #"_embeded.user"
I am using the DynamoDB SDK v2 . I can scan the database however I am struggling to query it for a specific results. I don't know if I have the DB setup wrong or I am doing the query wrong.
When I use
- (void)getTableRow:(NSString *)rangeKey {
AWSDynamoDBObjectMapper *dynamoDBObjectMapper = [AWSDynamoDBObjectMapper defaultDynamoDBObjectMapper];
[[dynamoDBObjectMapper load:[SonicUserTableRow class]
hashKey:#"UserId"
rangeKey:rangeKey] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task) {
if (!task.error) {
SonicUserTableRow *tableRow = task.result;
NSLog (#"Table Row %#", tableRow);
} else {
//Catch Error
}
return nil;
}];
}
I am calling it using [self getTableRow:#" ENTER UNIQUE USER ID "];
However I am getting the error
The provided key element does not match the schema
How can I fix this?
Note I am using the new Amazon SDK v2.
My Database
HASH & RANGE KEYS
SonicUserTableRow .m
+ (NSString *)dynamoDBTableName {
return #"SonicUsers";
}
+ (NSString *)hashKeyAttribute {
return #"UserId";
}
+ (NSString *)rangeKeyAttribute {
return #"Username";
}
SonicUserTableRow .h
#interface SonicUserTableRow : AWSDynamoDBModel <AWSDynamoDBModeling>
#property (nonatomic, strong) NSString *UserId;
#property (nonatomic, strong) NSString *Username;
#property (nonatomic, strong) NSString *profileImage;
#property (nonatomic, strong) NSString *active;
#property (nonatomic, strong) NSString *email;
#property (nonatomic, strong) NSString *flags;
#property (nonatomic, strong) NSString *attuned;
I have UserId value UserIdString: us-east-1:4ae0a93a-59a6-45fd-80c8-ff6b99f1d152 in the database so am trying to call for example: [self getTableRow:#"us-east-1:4ae0a93a-59a6-45fd-80c8-ff6b99f1d152"];
If DropId is a hash key of your table, you can use - load:hashKey:rangeKey: to load a single item.
I have the json
{"Types":{
"food":[{"cve":"1","description":"Pizza"},{"cve":"2","description":"Restaurant"},{"cve":"3","description":"Cafe"}],
"Health":[{"cve":"3","description":"Pharmacy"},{"cve":"4","description":"Hospital"}]
} }
Types.h
#import <Foundation/Foundation.h>
#interface Types: NSObject
#property (nonatomic, copy) NSDictionary *types;
#end
Types.m
#import "Types.h"
#import <Motis/Motis.h>
#import "SubTipo.h"
#implementation Types
+ (NSDictionary*)mts_mapping
{
return #{#"types": mts_key(types),};
}
#end
Subtype.h
#import <Foundation/Foundation.h>
#interface Subtype: NSObject
#property (nonatomic, assign) int cve;
#property (nonatomic, copy) NSString *description;
#end
Subtype.m
#import "Subtype.h"
#import <Motis/Motis.h>
#implementation Subtype
+ (NSDictionary*)mts_mapping
{
return #{#"cve": mts_key(cve),
#"description": mts_key(description),
};
}
#end
I deserialize with
Types * values=[[Types alloc]init];
NSDictionary * jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
[values mts_setValuesForKeysWithDictionary:jsonObject ];
I get NSDictionary with NSArray of NSDictionary
but I need NSDictionary with NSArray of Subtypes
I try with
+ (NSDictionary*)mts_arrayClassMapping
{
return #{mts_key(types): Subtype.class};
}
but wasn't successful
How can I get these with Motis
As far as I see, your Types object is not properly defined. If you have an attribute of type NSDictionary* and the JSON received is a Dictionary, Motis won't perform any automatic conversion as the types already match (you are receiving a dictionary and your attribute is of type NSDictionary).
Therefore, you must implement your Type object following your JSON structure. This means that your Type object must have two properties of type array, one for food and one for health. Then, using the method +mts_arrayClassMapping you can specify the content type of the arrays to Subtype.
Here the implementation:
// ***** Type.h file ***** //
#interface Type: NSObject
#property (nonatomic, strong) NSArray *food;
#property (nonatomic, strong) NSArray *health;
#end
// ***** Type.m file ***** //
#implementation Type
+ (NSDictionary*)mts_mapping
{
return #{#"food": mts_key(food),
#"Health": mts_key(health),
};
}
+ (NSDictionary*)mts_arrayClassMapping
{
return #{mts_key(food): Subtype.class,
mts_key(health): Subtype.class,
};
}
#end
Regarding the implementation of Subtype, yours is already correct. However, you should not use the property name description as it is already being used by NSObject:
// ***** Subtype.h file ***** //
#interface Subtype: NSObject
#property (nonatomic, assign) NSInteger cve;
#property (nonatomic, copy) NSString *theDescription;
#end
// ***** Subtypes.m file ***** //
#implementation Subtype
+ (NSDictionary*)mts_mapping
{
return #{#"cve": mts_key(cve),
#"description": mts_key(theDescription),
};
}
#end
Finally, as you list above, you can map your JSON, but first you will have to extract the "dictionary" for key Types, which you will map to your "Type" model object.
// Get the json data
NSDictionary * jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
// Extract the JSON dictionary of types.
NSDictionary *jsonType = [jsonObject objectForKey:#"Types"];
// Create a Type object
Type *type = [[Type alloc] init];
// Map JSON contents to the type object with Motis
[type mts_setValuesForKeysWithDictionary:jsonType];
Hoping this fixes your issue.