Restkit mapping POST Response - objective-c

I am trying to map a POST response via the code below, but when the didLoadObjects is reached Restkit is trying to map the same object as I am trying to POST (POSTing a Foo and want it to map Bar, but RestKit is trying to map the return to Foo).
[self.objectManager sendObject:mySyncInstance toResourcePath:url usingBlock:^(RKObjectLoader* postLoader) {
postLoader.delegate = aDelegate;
postLoader.objectMapping = [self.objectManager.mappingProvider objectMappingForClass:[Bar class]];
postLoader.method = RKRequestMethodPOST;
postLoader.userData = kUserDefaultsAttendanceReads;
postLoader.serializationMIMEType = RKMIMETypeJSON;
postLoader.serializationMapping
[postLoader setUsername:[prefs objectForKey:kCurrentUsername]];
[postLoader setPassword:[prefs objectForKey:kCurrentPassword]];
}];// end sendObject

The solution was to set rootKeyPath.
myPostReturnMapping.rootKeyPath = #"persons";
"persons": [
{ "id": "1",
"firstname": "hans",
"lastname": "maier",
"genre": "m"
},
{ "id": "2",
"firstname": "michael",
"lastname": "schmidt",
"genre": "w"
}]

Related

Get the value from the response based on a condition and store it to a variable

I would like to get the value from the response based on a condition and store it to a variable.
In the below JSON, I would like to store the value when the name matches to something I prefer. Is there a way to achieve this using Karate API?
{
"results": [
{
"name": "Sample1",
"email": "sample1#text.com",
"id": "U-123"
},
{
"name": "Sample2",
"email": "sample2#text.com",
"id": "U-456"
},
{
"name": "Sample3",
"email": "sample3#text.com",
"id": "U-789"
}
]
}
So after reading the comment, my interpretation is to "find" the id where name is Sample2. Easy, just use a filter() operation, refer the docs: https://github.com/karatelabs/karate#jsonpath-filters
Instead of using a filter, I'm using the JS Array find() method as a very concise example below:
* def response =
"""
{ "results": [
{ "name": "Sample1", "email": "sample1#text.com", "id": "U-123" },
{ "name": "Sample2", "email": "sample2#text.com", "id": "U-456" },
{ "name": "Sample3", "email": "sample3#text.com", "id": "U-789" }
]
}
"""
* def id = response.results.find(x => x.name == 'Sample2').id
* match id == 'U-456'
Take some time to understand how it works. Talk to someone who knows JS if needed.

Inserting and removing values within a collection array

I'm new to working with MongoDb using Express. I currently have a collection that has an array within an object. The array is meant to hold an unlimited number of values.
My question is when I add a new item to that array in the collection, do I always have to pass all the values in the object?
For example, with the following collection. Say I wanted to add a new contact.
{
"owner": "Tom Smith",
"age": "29",
"contacts": [
{
"firstname": "Fred",
"lastname": "Anderson",
"age": "22"
},
{
"firstname": "Linda",
"lastname": "Smith",
"age": "32"
},
{
"firstname": "Tom",
"lastname": "James",
"age": "42"
},
{
"firstname": "Cal",
"lastname": "Hallaway",
"age": "57"
}
],
"city": "New York"
}
Do I need to explicitly declare all my values in the object I pass to the end point?
Example:
obj.owner = 'Tom Smith';
obj.age = '29';
obj.contacts.firstname = 'Fred';
obj.contacts.lastname = 'Anderson';
obj.contacts.age = '22';
... etc.
and then add my new contact and push the full object to the endpoint to update?
Is there a way that I can just add a new contact without pushing all the data that already exists in the collection?
To add a new data in a nested attribute array:
Model.findOneAndUpdate({
_id: 'THE ID OF YOUR GYUS'
}, {
$push: {
contacts: {
firstname: 'TOTO',
lastname: 'TITI',
age: 42,
},
},
});

RestKit: JSON mapping doesn't work Objective-c

I use the RestKit framework to connect to a rest webservice.
How should the mapping look like if i want to have the resultlistEntries.
I've got a JSON-response like this:
{
"resultlist.resultlist": {
"paging": {
"numberOfHits": 69978,
"numberOfPages": 3499,
"pageNumber": 1,
"pageSize": 20
},
"resultlistEntries": [
{
"#numberOfHits": "69978",
"#realEstateType": "7",
"resultlistEntry": [
{
"#creation": "2013-01-15T16:36:00.000+01:00",
"resultlist.realEstate": {
"#id": "68014527",
"#xsi.type": "search:Office",
"calculatedPrice": {
"currency": "EUR",
"marketingType": "RENT_PER_SQM",
"priceIntervalType": "MONTH",
"value": 4.5
},
"commercializationType": "RENT",
"courtage": {
"hasCourtage": "YES"
},
"floorplan": "false",
"netFloorSpace": 155,
"price": {
"currency": "EUR",
"marketingType": "RENT",
"priceIntervalType": "MONTH",
"value": 697.5
},
"totalFloorSpace": 155
}
}
]
}
]
}
}
and the following RestKit Code
NSString *pathPattern = #"resultlist.resultEntries";
NSString *keyPath = #"resultEntry";
RKResponseDescriptor *responseDescriptor =
[RKResponseDescriptor responseDescriptorWithMapping:mapping
pathPattern:pathPattern
keyPath:keyPath
statusCodes:statusCodes];
the result is the following:
2013-01-15 16:49:00.102 RestKit_final[31840:c07]
Failed with error: No response descriptors match the response loaded.
Whats wrong ?
pathPattern is used to specify an endpoint where the response descriptor will be used. For example, #"/hotels/premium" as a pathPattern will mean that the response descriptor will not apply if you call #"/hotels/cheap". You can set this to nil, but I always like to keep my response descriptors as specific as possible.
The keypath for the resultlistEntry array in the JSON response would technically be resultlist.resultlist.resultlistEntries, but you may have some issues with the resultlist.resultlist part. I would suggest changing your API to return simply resultList then your required keypath will be resultlist.resultlistEntries.

RestKit - Hydrate array of foreign keys

I have the following JSON:
{
"users": [
{"id": "1", "name": "John Doe"},
{"id": "2", "name": "Bill Nye"}
],
"groups": [
{"id": "1", "name": "Group1", "users": ["1", "2"]},
{"id": "2", "name": "Group2", "users": ["1"]}
]
}
...and a Core Data model with User and Group objects. The group object has a to-many relationship (NSSet) to users.
I have found the following thread that seems to indicate that this is possible, but contains no explanation of how such a mapping is to be performed:
https://github.com/RestKit/RestKit/issues/284
How do I perform this mapping such that each Group's "users" relationship is properly connected?
Note: I have mappings set up that correctly map the JSON users and groups to their respective Core Data objects. However, each group's "users" NSSet is empty.
So, I figured this out using RestKit 0.20(pre2).
JSON needed to be changed to the following (note the attribute names in the group's users array):
{
"users": [
{"id": "1", "name": "John Doe"},
{"id": "2", "name": "Bill Nye"}
],
"groups": [
{"id": "1", "name": "Group1", "users": [{"id" : "1"}, {"id" : "2"}]},
{"id": "2", "name": "Group2", "users": [{"id" : "1"}]}
]
}
Then, the following mappings:
RKEntityMapping *userMapping = [RKEntityMapping mappingForEntityForName:#"User" inManagedObjectStore:managedObjectStore];
userMapping.identificationAttributes = #[#"id"];
[userMapping addAttributeMappingsFromArray:#[#"id", #"name"]];
RKEntityMapping *groupMapping = [RKEntityMapping mappingForEntityForName:#"Group" inManagedObjectStore:managedObjectStore];
groupMapping.identificationAttributes = #[#"id"];
[groupMapping addAttributeMappingsFromArray:#[#"id", #"name"]];
[groupMapping addRelationshipMappingWithSourceKeyPath:#"users" mapping:userMapping];
And finally, the following responseDescriptors:
RKResponseDescriptor *userResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:classMapping pathPattern:#"/api/allthejson" keyPath:#"users" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
RKResponseDescriptor *groupResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:classMapping pathPattern:#"/api/allthejson" keyPath:#"groups" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[objectManager addResponseDescriptorsArray:#[userResponseDescriptor, groupResponseDescriptor]];
Then get your objects using RKObjectManager's getObjectsAtPath:parameters:success:failure method and your done!
RestKit has many issues especially when it comes to modeling relationships. Debugging the mappings can be daunting.
Here is some code that deals with what you describe without RestKit.
NSArray *userArray;
// an array populated with NSManagedObjects
// correctly converted from JSON to the User entity
NSArray *groups = [jsonObject objectForKey:#"groups"];
for (NSDictionary *d in groups) {
Group *g = [NSEntityDescription insertNewObjectForEntityForName:#"Group"
inManagedObjectContext:_managedObjectContext];
g.id = #([d[#"id"] intValue]);
g.name = d[#"name"];
NSArray *users = d[#"users"];
for (NSString *s in users) {
User *u = [[userArray filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:#"id = %#", #([s intValue])]]
objectAtIndex:0];
[g addUsersObject:u];
}
}
// save

Read Specific Character from NSSTRING and save them in NSDictionary (LinkedIn Api)

I am using Linkedin Api in my Iphone App.I want to read the Connection Names and their Profession.In First Step I read the user name and Professional by using the Following Api.
http://api.linkedin.com/v1/people/~
It return the following String and I convert that string in to NSDictionary .Its Work Fine.
====================================
coming string is equql to {
"headline": "Computer Software Professional",
"lastName": "Ahmed",
"siteStandardProfileRequest": {"url": "http://www.linkedin.com/profile?viewProfile=&key=86794265&authToken=ZBFd&authType=name&trk=api*a135617*s143990*"},
"firstName": "Umair"
}
========================================
Nsstring to NSDictionary conversion:-
Data coming from LinkedIn site
NSString *responseBody = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"coming string is equql to %#",responseBody);
NSDictionary *profile = [responseBody objectFromJSONString];
[responseBody release];
if ( profile )
{
name.text = [[NSString alloc] initWithFormat:#"%# %#",
[profile objectForKey:#"firstName"], [profile objectForKey:#"lastName"]];
headline.text = [profile objectForKey:#"headline"];
}
The Above code Work Fine.
But when i use Connection Api.(For Linkedin Friends)
http://api.linkedin.com/v1/people/~/connections
I receive the following response in String.
========================================================================================
coming string is equql to {
"values": [
{
"headline": "--",
"id": "jrzlnzmKgH",
"lastName": "ahmad",
"pictureUrl": "http://media.linkedin.com/mpr/mprx/0_7bH7Ex4_zD3EJFYkDFRKEjehBacbMF0kD8prEjV0eIiBQ_HXiT4_XgmAM8BZVhOemkol5sXLbyGk",
"location": {
"name": "United Arab Emirates",
"country": {"code": "ae"}
},
"siteStandardProfileRequest": {"url": "http://www.linkedin.com/profile?viewProfile=&key=87979190&authToken=RO5n&authType=name&trk=api*a135617*s143990*"},
"apiStandardProfileRequest": {
"headers": {
"values": [{
"name": "x-li-auth-token",
"value": "name:RO5n"
}],
"_total": 1
},
"url": "http://api.linkedin.com/v1/people/jrzlnzmKgH"
},
"firstName": "junaid"
},
{
"headline": "Field Testing Engineer at SENSYS",
"id": "iZbYn6whQT",
"lastName": "Ali Ayub",
"location": {
"name": "Pakistan",
"country": {"code": "pk"}
},
"siteStandardProfileRequest": {"url": "http://www.linkedin.com/profile?viewProfile=&key=66010848&authToken=k_Wj&authType=name&trk=api*a135617*s143990*"},
"apiStandardProfileRequest": {
"headers": {
"values": [{
"name": "x-li-auth-token",
"value": "name:k_Wj"
}],
"_total": 1
},
"url": "http://api.linkedin.com/v1/people/iZbYn6whQT"
},
"industry": "Government Administration",
"firstName": "Prince"
},
{
"headline": "Student at comsats",
"id": "AZtfwY31D2",
"lastName": "Anwar",
"location": {
"name": "Pakistan",
"country": {"code": "pk"}
},
"siteStandardProfileRequest": {"url": "http://www.linkedin.com/profile?viewProfile=&key=106573059&authToken=4_ll&authType=name&trk=api*a135617*s143990*"},
"apiStandardProfileRequest": {
"headers": {
"values": [{
"name": "x-li-auth-token",
"value": "name:4_ll"
}],
"_total": 1
},
"url": "http://api.linkedin.com/v1/people/AZtfwY31D2"
},
"industry": "Computer Networking",
"firstName": "Irfan"
},
{
"headline": "WiMAX RF Planning Engineer at IACGRP",
"id": "ERjOSiKbPo",
"lastName": "Arsil",
"pictureUrl": "http://media.linkedin.com/mpr/mprx/0_T_Ic9x0GWkhvZ7R13LHX9juCdb-ZsoI1iC0e9pDY9C6e5mpPD5RRZyMKFdtbJDo088ddJU1s5_py",
"location": {
"name": "Pakistan",
"country": {"code": "pk"}
},
"siteStandardProfileRequest": {"url": "http://www.linkedin.com/profile?viewProfile=&key=35285050&authToken=ouYS&authType=name&trk=api*a135617*s143990*"},
"apiStandardProfileRequest": {
"headers": {
"values": [{
"name": "x-li-auth-token",
"value": "name:ouYS"
}],
"_total": 1
},
"url": "http://api.linkedin.com/v1/people/ERjOSiKbPo"
},
=====================================================
Now I want to convert it in to NsDictionary With key Value Like Firstname,Lastname etc.How can I do This.
Thanks in Advance
You need to use a JSON library for iPhone. One of them is the TouchJSON library, you can see this question to learn more.
Use Json Libraray for Retreive your Values.Its so Simple.Thanks