Posting an array of objects not working with Restkit [duplicate] - ios

This question already has an answer here:
Restkit request not sending parameters
(1 answer)
Closed 8 years ago.
I have the following two entities
#interface MEContactInfo : NSObject
#property (nonatomic,strong) NSString* phone ;
#property (nonatomic,strong) NSString* email;
#end
#interface MEContact : NSObject
#property (nonatomic,strong) NSString* _id ;
#property (nonatomic,strong) NSString* lastName;
#property (nonatomic,strong) NSString* firstName;
#property (nonatomic,strong) NSString* data ;
#property (nonatomic,strong) NSMutableArray* contactInfos ;
#end
The second entity contact contains the array of contact infos. Now I want to post this to my server but I am not able to do so. My mappings are as following:
RKObjectMapping* contactMapping = [RKObjectMapping mappingForClass:[MEContact class]];
[contactMapping addAttributeMappingsFromArray:#[#"_id",#"lastName",#"firstName",#"data"]];
RKObjectMapping* contactInfosMapping = [RKObjectMapping mappingForClass:[MEContactInfo class]];
[contactInfosMapping addAttributeMappingsFromArray:#[#"email",#"phone"]];
[contactMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"contactInfos" toKeyPath:#"contactInfos" withMapping:contactInfosMapping]];
My request descriptor is as following:
requestDescriptor = [RKRequestDescriptor
requestDescriptorWithMapping:[contactMapping inverseMapping]
objectClass: [MEContact class]
rootKeyPath:nil method:RKRequestMethodAny];
Now when I post something like this:
{ firstName:”abc”,
lastName:”xyz”,
contactInfos: [{
email:”test#test.com”,
phone:”9999999999”
}]
}
I receive
{
firstName:”abc”,
lastName:”xyz”,
contactInfos: [ ”test#test.com”,”9999999999”]
}
If I have multiple entries in the contactInfos array, they all are appended to the contactInfos array I receive on the server side. Basically the contactInfo object is flattening in an array. Can you please let me know how I can fix this.

I got it to work. Everything above was correct. The problem was that data was not going as JSON to the server. The solution was that I had to set request serialization MimeType which can be done by doing this
[objectManger setRequestSerializationMIMEType:RKMIMETypeJSON];
Thanks

Related

do i need to create mapping for all objects of json that i get?

I have questions about rest kit.
do i need to create mapping for all objects of json that i get ? or i can provide mapping only fore some of this objects and restkit will work properly even if I did not create mapping for some objects that I am loading from internet?
for example there are this classes
#interface RKAUser : NSObject
#property (strong, nonatomic) NSString* nameString;
#property (strong, nonatomic) RKCard* card;
#end
#interface RKACard : NSObject
#property (strong, nonatomic) NSString* numberString;
#end
+ (RKMapping *)userMapping {
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[RKAUser
class]];
[mapping addAttributeMappingsFromArray:#[#"nameString"]];
return mapping;
}
I have json where is information for about 20 users
in this json there are all user information including nameString and his cards numberString.
but I create mapping only for nameString and did not create mapping for card
question for this example will be would this code work or it will crash maybe because I did not provide all mapping
another question
can i use restkit for mapping any json information or not?
does information should be definitely from some kind of rest server or rest kit can map json information from any server? will it work if information is not from server?
You only need to implement properties that you used when creating your mappings.
JSON doesn't need to come from the server. You can take any JSON document, then parse it yourself and use RKMapperOperation with the result.
RKMapperOperation *operation = [[RKMapperOperation alloc] initWithRepresentation:parsedJSON mappingsDictionary:yourMappingsDictionary];
NSError *error = nil;
[operation execute:&error];
if (!error) {
NSArray *result = mapper.mappingResult.array;
}

RESTKit - post a large array of objects to server

How can I post an array of objects to my server with RESTKit?
I have a custom object called Contact which have some properties like name, phone etc. I would like to send an array of these Contact objects to the server.
The method I know for this is postObject:path:parameters:success:failure, but what object I put here? If I put Contact - how will it know it is an array? and if I put NSArray, how will it know it is a Contact?
My Contact object header file is:
#interface Contact : NSObject
#property (strong, nonatomic) NSString *name;
#property (strong, nonatomic) NSString *phone;
#property (nonatomic) NSInteger order;
#property (strong, nonatomic) NSString *firstName;
#property (strong, nonatomic) NSString *lastName;
#end
my response mapping is:
RKObjectMapping *personMapping = [RKObjectMapping mappingForClass:[Contact class]];
[personMapping addAttributeMappingsFromDictionary:#{
#"username": #"name",
#"firstname" : #"firstName",
#"lastname" : #"lastName",
}];
my response descriptor is:
RKResponseDescriptor *personResponseDescriptorForArrayOfPhones =
[RKResponseDescriptor responseDescriptorWithMapping:personMapping
method:RKRequestMethodANY
pathPattern:#"getUsersInfoByPhones"
keyPath:nil
statusCodes:[NSIndexSet indexSetWithIndex:200]];
my request mapping is:
RKObjectMapping *personRequestMapping = [RKObjectMapping requestMapping ];
[personRequestMapping addAttributeMappingsFromDictionary:#{
#"name": #"username",
#"firstName" : #"firstName",
#"lastName" : #"lastName",
#"phone" : #"usernames"
}];
my request descriptor is:
RKRequestDescriptor *personRequestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:personRequestMapping
objectClass:[Contact class]
rootKeyPath:nil
method:RKRequestMethodAny];
Does this implementation looks good?
Also, this array I want to send to the server could be very big, around 200-1000 objects. Is that possible with RESTKit?
Update: Actually, I would prefer to send an array of strings (which would be phone numbers), and get from the server the Contact objects I have. How can I set RESTKit to post the array of strings and to expect a response of an array of Contact objects?
The json I need to send looks like this:
{
"usernames":["11","22"]
}
the json I expect to get is:
[
{
"_id" : "53e23a54e811310000955f70",
"profileUpdatesCounter" : 3,
"lastname" : "SMITH",
"firstname" : "BOB",
"username" : "11"
}
]

RestKit - Not key-value coding compliant, no root in JSON

I've been trying to map the following object from the JSON response and from everything I see in the console output, there isn't any reason why the mapping isn't successful - I appreciate if anyone could have a check and see:
#interface RKElectionsModel : NSObject
#property (nonatomic, assign) bool isActive;
#property (nonatomic, strong) NSNumber *electionID;
#property (nonatomic, strong) NSString *title;
#property (nonatomic, strong) NSString *summary;
#property (nonatomic, strong) NSNumber *availableSeats;
#property (nonatomic, strong) NSNumber *candidatesCount;
#property (nonatomic, strong) NSNumber *withdrawnCount;
#property (nonatomic, strong) NSSet *candidates;
#end
/**
* Election Detail Mapping: Getting all election details, we have some extra information from
* the API call
*
*/
RKObjectMapping *electionDetailsMapping = [RKObjectMapping mappingForClass:[RKElectionsModel class]];
// Map JSON -> entities
[electionDetailsMapping addAttributeMappingsFromDictionary:#{
#"id": #"electionID",
#"title": #"title",
#"summary": #"summary",
#"active": #"isActive",
#"availableSeats": #"availableSeats",
#"candidatesCount": #"candidatesCount",
#"withdrawnCount": #"withdrawnCount"
}];
// Register our mappings with the provider
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:electionDetailsMapping pathPattern:#"/api/elections/:electionID/all" keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
Console output on pastebin and any examples of the JSON response you can visit here
Appreciate any help,
Lewis
Seems like your trying to map a NSString to NSNumber.
In your NSObject try to add the following validation and transform the string you receive from the server to a NSNumber when the mapping starts.
- (BOOL)validateAvailableSeats:(id *)ioValue error:(NSError **)outError {
// Force the value to be a NSNumber
*ioValue = [NSNumber numberWithDouble:[(NSString*)value doubleValue] ]
return YES;
}
In the RestKit Wiki you'll find more transformations for your values.

Restkit mapping complex nested array

I am trying to use restkit to read/parse an xml feed. which contains a nested array of artists. I can map other relationships but am unclear what I am to do with the artist relationship below.
My dataset looks like:
<JamBase_Data>
<Results_Title>Jersey City, NJ</Results_Title>
<event>
<event_id>1896611</event_id>
<artists>
<artist>
<artist_id>96929</artist_id>
<artist_name>The Happy Problem</artist_name>
</artist>
<artist>
<artist_id>29817</artist_id>
<artist_name>Craig Greenberg</artist_name>
</artist>
</artists>
<event_date>1/9/2013</event_date>
<venue>
<venue_id>48553</venue_id>
<venue_name>The Cake Shop</venue_name>
<venue_city>New York</venue_city>
<venue_state>NY</venue_state>
<venue_zip>10002</venue_zip>
</venue>
<event_url>
http://www.jambase.com/Shows/Event.aspx?eventID=1896611
</event_url>
</event>
</JamBase_Data>
Mappings:
RKObjectMapping *eventMapping = [RKObjectMapping mappingForClass:[Event class]];
RKObjectMapping *artistMapping = [RKObjectMapping mappingForClass:[Artist class]];
RKObjectMapping *venueMapping = [RKObjectMapping mappingForClass:[Venue class]];
[artistMapping mapKeyPathsToAttributes: #"artist_name",#"artist_name", nil];
[venueMapping mapKeyPathsToAttributes: #"venue_city",#"venue_city",#"venue_state",#"venue_state", #"venue_name", #"venue_name", nil];
[objectManager.mappingProvider setMapping:eventMapping forKeyPath:#"JamBase_Data.event"];
[eventMapping mapKeyPath:#"artists" toRelationship:#"artists" withMapping:artistMapping];
[eventMapping mapKeyPath:#"venue" toRelationship:#"venue" withMapping:venueMapping];
Venue.h
#interface Event : NSObject
#property (nonatomic, strong) NSSet *artists;
#property (strong, nonatomic) Venue *venue;
#end
Artist.h
#interface Artist : NSObject
#property (nonatomic, strong) NSNumber *artist_id;
#property (nonatomic, strong) NSNumber *artist_name;
I can get venue to map correctly, but cannot figure out how to get Artists to map. Is there something i need to do to tell the object manager to make an coming off of the event?
Any help would be greatly appreciated as this is my first foray into iOS development.
The Artists object you see in the XML translates to an NSArray. Now that contains objects of type Artists. Have you thought about it that way?

Parsing JSON using RestKit

I have been using RestKit for sometime but some APIs have changed in the latest version and I'm no longer able to parse simple JSON.
Here's the payload I have:
{
"result":true,
"items":[
{
"id":"1",
"receiver":"11011101"
},
{
"id":"2",
"receiver":"11011101"
}
]
}
How can I parse the contents of the "items" dictionary as instances of the object Conversation I have created?
Using the code below doesn't work (objects are never mapped):
RKObjectMapping* conversationMapping = [RKObjectMapping mappingForClass:[Conversation class]];
[conversationMapping mapKeyPath:#"id" toAttribute:#"id"];
[conversationMapping mapKeyPath:#"receiver" toAttribute:#"receiver"];
[[RKObjectManager sharedManager].mappingProvider setMapping:conversationMapping forKeyPath:#"items"];
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:#"/getConversations" delegate:self];
Conversation class
#interface Conversation : NSObject {
NSString *id;
NSString *receiver; }
+ (void)objectMapping;
#property (nonatomic, strong) NSString *id; #property (nonatomic, strong) NSString *receiver;
#end
#implementation Conversation
#synthesize id;
#synthesize receiver;
+ (void)objectMapping {
RKObjectMapping* conversationMapping = [RKObjectMapping mappingForClass:[Conversation class]];
[conversationMapping mapKeyPath:#"id" toAttribute:#"id"];
[conversationMapping mapKeyPath:#"receiver" toAttribute:#"receiver"];
[[RKObjectManager sharedManager].mappingProvider setMapping:conversationMapping forKeyPath:#"items"];
}
#end
How is your root object defined (the one that holds "result" and your Conversation "items")? That should look something like this:
#interface MyResponse
#property (nonatomic, strong) NSArray* items;
#property (nonatomic, assign) BOOL result;
with the appropriate mapping for that as well.
I solved the problem. It was something totally not related to RestKit. The content type of the response coming back from the server was not set to JSON, after fixing that object mapping worked fine.

Resources