RestKit: JSON mapping doesn't work Objective-c - 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.

Related

karate.repeat creates a malformed JSON that is unable to traverse

I have a scenario where I need to call a secondary feature file that contains an API call where the response is a JSON object. However, I need to call this scenario multiple times, so I am using karate.repeat to achieve this. However, the resulting response is a malformed JSON that I cannot traverse.
This is what I am doing:
* def fun = function(i){ return karate.call('abc.feature#abc', value)}
* def loop = karate.repeat(2, fun)
* karate.log(loop)
The response I get is:
{
"Total_packages1": {
"package1": {
"tags": [
"kj21",
"j1",
"sj2",
"z1"
],
"expectedResponse": [
{
"firstName": "Name",
"lastName": "lastName",
"purchase": [
{
"title": "title",
"category": [
"a",
"b",
"c"
]
}
]
}
]
}
}
}
{
"Total_packages2": {
"package2": {
"tags": [
"kj212",
"j12",
"sj22",
"z12"
],
"expectedResponse": [
{
"firstName": "Name2",
"lastName": "lastName2",
"purchase": [
{
"title": "title2",
"category": [
"a2",
"b2",
"c2"
]
}
]
}
]
}
}
}
As you can see, Total_packages2 starts malformed. I need to grab the "tags" values from each package, however, I cannot simply do Total_packages1.package1.tags like I could with a single response in the JSON.
If I cannot achieve what I need by karate.repeat, is there another method that is recommended for looping like this? I haven't found anything in the documentation for this particular scenario.
Don't use karate.repeat() use call with a JSON array. Read this part of the docs: https://github.com/karatelabs/karate#data-driven-features

Fetch data in a POST Request in asp.net core

I am using an external web link to get data and fetch it to json The reason why I need to handle it by the controller is to filter the data of it. Sadly, an api link was programmatically incorrect because instead of requesting it as GET method, it was programmed as POST method. I had this code simple code below but the return was a header data not the actual data of the api.
[HttpPost, Route("get/subproject")]
public ActionResult subproject()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(#"https://thisisjustasample.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage hrm = client.PostAsync("/api/new/get/subproject/details/get_dto", null).Result;
return Ok(hrm);
}
}
The output of the code above is this.
{
"version": "1.1",
"content": {
"headers": [
{
"key": "Content-Length",
"value": [
"29942142"
]
},
{
"key": "Content-Type",
"value": [
"application/json; charset=utf-8"
]
},
{
"key": "Expires",
"value": [
"-1"
]
}
]
}
}
What I need is this data below.
{
"sub_project_id": 267892,
"engineeringMigrationId": 0,
"modality_id": 21,
"id": null,
"reportID": null,
"month": null,
"year": null,
"cycle_id": 204
}
Any help would be appreciated. Thanks in advance.
Don't return hrm directly, If you want to get the response data, you need return.
hrm.Content.ReadAsStringAsync().Result
Demo
1.return Ok(hrm);
2.return Ok(hrm.Content.ReadAsStringAsync().Result);

GraphJSON serialization in Gremlin.Net

I'm trying to query the TinkerPop server (hosted inside docker container) via CosmosDB client library, which uses under the hood Gremlin.Net. So I managed to connect it and insert the data, here's intercepted WebSocket request:
!application/vnd.gremlin-v1.0+json{
"requestId": "b64bd2eb-46c3-4095-9eef-768bca2a14ed",
"op": "eval",
"processor": "",
"args": {
"gremlin": "g.addV(\"User\").property(\"UserId\",2).property(\"CustomerId\",1)"
}
}
The response:
{
"requestId": "b64bd2eb-46c3-4095-9eef-768bca2a14ed",
"status": {
"message": "",
"code": 200,
"attributes": {
"host": "/172.19.0.1:38848"
}
},
"result": {
"data": [
{
"id": 0,
"label": "User",
"type": "vertex",
"properties": {}
}
],
"meta": {}
}
}
Problem is that I see those properties when I'm connected via gremlin console
gremlin> g.V().hasLabel("User").has("CustomerId",1).has("UserId",2).limit(1).valueMap()
==>{UserId=[2], CustomerId=[1]}
Also, I'm able to query the TinkerPop server with Gremlin.Net:
!application/vnd.gremlin-v1.0+json{
"requestId": "de35909f-4bc1-4aae-aa5f-28361b3c0933",
"op": "eval",
"processor": "",
"args": {
"gremlin": "g.V().hasLabel(\"User\").has(\"CustomerId\",1).has(\"UserId\",2).limit(1)"
}
}
But it returns a payload with zero-valued ID and without any properties included:
{
"requestId": "de35909f-4bc1-4aae-aa5f-28361b3c0933",
"status": {
"message": "",
"code": 200,
"attributes": {
"host": "/172.19.0.1:38858"
}
},
"result": {
"data": [
{
"id": 0,
"label": "User",
"type": "vertex",
"properties": {}
}
],
"meta": {}
}
}
Tried to swap between GraphSON v1, v2, v3 with no luck. Documentation says that script serializers should include all the properties. Do I have to tweak the config somehow to make this work and return properties?
So it seems that with a version of 3.4 of the Gremlin server ReferenceElementStrategy
was added by default to traversals, to preserve compatibility between binary and script serializers. In our case we wanted to mimic the behavior of the CosmosDB, so to adjust and receive desired behavior just remove the strategy from init script (in our case it was empty-sample.groovy
globals << [g : graph.traversal().withStrategies(ReferenceElementStrategy.instance())]
to
globals << [g : graph.traversal()]

How do you get all the email body parts? And how do you know how many parts exist?

I'm trying to read emails responded by the Gmail API.
I have trouble accessing all the "parts". And don't have great ways to traverse through the response. I'm also lost as to how many parts can exist so that I can make sure I read the different email responses properly. I've shortened the response below...
{ "payload": { "mimeType": "multipart/mixed", "filename": "",
], "body": { "size": 0 }, "parts": [ {
"body": {
"size": 0
},
"parts": [
{
"partId": "0.0",
"mimeType": "text/plain",
"filename": "",
"headers": [
{
"name": "Content-Type",
"value": "text/plain; charset=\"us-ascii\""
},
{
"name": "Content-Transfer-Encoding",
"value": "quoted-printable"
}
],
"body": {
"size": 2317,
"data": "RGVhciBNSVQgQ2x1YiBWb2x1bnRlZXJzIGluIEFzaWEsDQoNCkJ5IG5vdyBlYWNoIG9mIHlvdSBzaG91bGQgaGF2ZSByZWNlaXZlZCBpbnZpdGF0aW9ucyB0byB0aGUgcmVjZXB0aW9ucyBpbiBib3RoIFNpbmdhcG9yZSBhbmQgSG9uZyBLb25nIHdpdGggUHJlc2lkZW50IFJlaWYgb24gTm92ZW1iZXIgNyBhbmQgTm92ZW1iZXIg"
}
},
{
"partId": "0.1",
"mimeType": "text/html",
"filename": "",
"headers": [
{
"name": "Content-Type",
"value": "text/html; charset=\"us-ascii\""
},
{
"name": "Content-Transfer-Encoding",
"value": "quoted-printable"
}
],
"body": {
"size": 9116,
"data": "PGh0bWwgeG1sbnM6dj0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp2bWwiIHhtbG5zOm89InVybjpzY2hlbWFzLW1pY3Jvc29mdC1jb206b2ZmaWNlOm9mZmljZSIgeG1sbnM6dz0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTpvZmZpY2U6d29yZCIgeG1sbnM6bT0iaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS9vZmZpY2UvMjA"
}
}
] }, {
"partId": "1",
"mimeType": "text/plain",
"filename": "",
"body": {
"size": 411,
"data": "X19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX18NClRoYW5rIHlvdSBmb3IgYWxsb3dpbmcgdXMgdG8gcmVhY2ggeW91IGJ5IGVtYWlsLCB0aGUgbW9zdCBpbW1lZGlhdGUgbWVhbnMgZm9yIHNoYXJpbmcgaW5mb3JtYXRpb24gd2l0aCBNSVQgYWx1bW5pLiANCklmIHlvdSB3b3VsZCBsaWtlIHRvIHVuc3Vic2NyaWJlIGZyb20gdGhpcyBtYWlsaW5nIGxpc3Qgc2VuZCBhIGJsYW5rIGVtYWlsIHRvIGxpc3RfdW5zdWJzY3JpYmVAYWx1bS5taXQuZWR1IGFuZCBwdXQgdGhlIGxpc3QgbmFtZSBpbiB0aGUgc3ViamVjdCBsaW5lLg0KRm9yIGV4YW1wbGU6DQpUbzogbGlzdF91bnN1YnNjcmliZUBhbHVtLm1pdC5lZHUNCkNjOg0KU3ViamVjdDogYXNpYW9mZg0K"
} } ] } }
Is there something I'm missing?
A MIME message is not just an array it's a full blown tree structure. So you'll have to traverse it to correctly handle it. Luckily JSON parsers are plentiful and the problem can easily be handled with recursion. In many languages there exist very useful email parsing libraries that can make accessing traditional parts (e.g. the text/plain or text/html displayable part, or attachments) not too laborious.
You'll have to set up walker functions to traverse through the json and pick out the bits you are after. Here is a part of what I wrote. This may help you jumpstart your code. NOTE: this is used inside of wordpress...hence the special jQuery call. Not needed if you do not need to use jquery inside wordpress.
function makeApiCall() {
gapi.client.load('gmail', 'v1', function() {
//console.log('inside call: '+myquery);
var request = gapi.client.gmail.users.messages.list({
'userId': 'me',
'q': myquery
});
request.execute(function(resp) {
jQuery(document).ready(function($) {
//console.log(resp);
//$('.ASAP-emailhouse').height(300);
$.each(resp.messages, function(index, value){
messageId = value.id;
var messagerequest = gapi.client.gmail.users.messages.get({
'userId': 'me',
'id': messageId
});//end var message request
messagerequest.execute(function(messageresp) {
//console.log(messageresp);
$.each(messageresp, responsewalker);
function responsewalker(key, response){
messagedeets={};
$.each(messageresp.payload.headers, headerwalker);
function headerwalker(headerkey, header){
if(header.name =='Date'){
d = new Date(header.value);
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
var formatteddate = curr_month+'/'+curr_date+'/'+curr_year;
messagedeets['date']=formatteddate;
//$('.ASAP-emailhouse').append('<p>'+header.value+'</p>');
}
if(header.name =='Subject'){
//console.log(header.value);
messagedeets.subject=header.value;
}
}
messagedeets.body = {};
$.each(messageresp.payload.parts, walker);
function walker(partskey, value) {
//console.log(value.body);
if (value.body.data !== "undefined") {
//console.log(value.body);
var messagebody = atob(value.body.data);
messagedeets.body.partskey = messagebody;
}
console.log(messagedeets);
$('.ASAP-emailhouse').append('<div class="messagedeets"><p class="message-date">'+messagedeets.date+': <span class="message-subject">'+messagedeets.subject+'</span></p><p>'+messagedeets.body.partskey+'</p></div>');
}//end responsewalker
//$('.ASAP-emailhouse').append('</li>');
}
//$('.ASAP-emailhouse').append('</ul>');
});//end message request
});//end each message id
});//end jquery wrapper for wordpress
});//end request execute list messages
});//end gapi client load gmail
}
The MIME parts you are looking for are in an array. JSON does not tell you up front how many items are in an array. Even MIME itself does not provide a way of knowing how many parts are present without looking at the entire message. You will just have to traverse the entire array to know how many parts are in it, and process each part as you encounter it.
To know how much parts exists, you can just use the Length property.
Example :
json.payload.parts.length
For your example, this property is 2 because there are 2 parts.

Restkit 0.20 Dynamic Nested Mapping

I am using Restkit 0.20 to map and store objects in core data. For basic mappings it works well, but it doesnt work for nested dynamic mappings. This is my example response:
[
{
"actor": {
"id": 7,
"first_name": "Murat",
"last_name": "Akbal"
},
"target": {
"content_type": "dress",
"type": {
"id": 1,
"name": "leggings",
"kind": "bottom"
},
"style": {
"id": 1,
"name": "sport"
},
"full_name": "Murat - sport leggings",
"id": 19,
}
},
{
"actor": {
"id": 7,
"first_name": "Murat",
"last_name": "Akbal"
},
"target": {
"content_type": "wardrobe",
"style": {
"id": 1,
"name": "sport"
},
"id": 38,
"season": "spring",
"name": "asdasd"
}
}
]
I use following entity mapping to map response:
//create entity mapping
RKEntityMapping *objectMapping = [RKEntityMapping mappingForEntityForName:#"Action"
inManagedObjectStore:[RKObjectManager sharedManager].managedObjectStore];
//create dynamic mapping
RKDynamicMapping *dynamicMapping = [RKDynamicMapping new];
//dressMapping and wardrobeMapping predefined mappings, they work well when mapping the wardobe and dress alone.
[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) {
if ([[representation valueForKey:#"content_type"] isEqualToString:#"wardrobe"]) {
return wardrobeMapping;
} else if ([[representation valueForKey:#"content_type"] isEqualToString:#"dress"]) {
return dressMapping;
}
return nil;
}];
[objectMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"target" toKeyPath:#"target" withMapping:dynamicMapping]];
//maps actor
[objectMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:#"actor" toKeyPath:#"actor" withMapping:actorMapping]];
And lastly, I register the objectMapping as response descriptor:
RKResponseDescriptor *responseDescriptor =
[RKResponseDescriptor responseDescriptorWithMapping:objectMapping
pathPattern:nil
keyPath:nil
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[[RKObjectManager sharedManager] addResponseDescriptor:responseDescriptor];
This doesn't work for my example response, gives the following error:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<Wardrobe 0x110e1a90> valueForUndefinedKey:]: the entity Wardrobe is not key value coding-compliant for the key "type".'
It asks "type" key which does not exist in wardrobe, but exists for dress. Somehow, it tries to map wardrobe with dress mapping. Do you have any idea about that issue?
fyi, type of target in coredata is transformable.
I found the problem. Actually it mapped response successfully, but when deleteLocalObjectsMissingFromMappingResult is preforming it throws an exception from this line:
id managedObjects = event.keyPath ? [objectsAtRoot valueForKeyPath:event.keyPath] : objectsAtRoot;
it seeks keyPath for all object at mapping results instead of each individual object. So in my situation it cannot find the "type" key for wardrobe because it does not exist. As a basic solution, I surrounded the code block with try-catch