How to map an array of arrays in Mantle - objective-c

Anybody got an idea of how to map this response to a mantle object?
I need to get these to an NSArray of custom classes. But the Mantle documentation has no mention on how to do this.
Thanks in advance.
[
[
{
"plu_id": "1744",
"name": "With egg",
"price": "2.00",
"group": null
}
],
[
{
"plu_id": "1745",
"name": "add roast chicken",
"price": "3.00",
"group": "1"
},
{
"plu_id": "1749",
"name": "add beef",
"price": "4.00",
"group": "1"
}
]
]

Please try the below snippet mentioned for an identical issue
+ (NSValueTransformer *)allRowsJSONTransformer
{
return [MTLValueTransformer transformerWithBlock:^id(NSArray *inSectionJSONArray) {
NSMutableArray *sectionArray = [[NSMutableArray alloc] initWithCapacity:inSectionJSONArray.count];
for( NSArray *section in inSectionJSONArray )
{
NSError *error;
NSArray *cardItemArray = [MTLJSONAdapter modelsOfClass:[CKMCardItem class] fromJSONArray:section error:&error];
if( cardItemArray != nil )
{
[sectionArray addObject:cardItemArray];
}
}
return sectionArray;
}];
}

Related

how to gat a value from an array which contain in an object and object already in an array while using json response?

[
{
"result": 1,
"max_qty": "10",
"msg": [
{
"product_id": "39",
"product_name": "Cabbage",
"product_price": "18",
"product_image": "product/39.jpg",
"product_description": "Fresh Cabbage",
"product_category": "1",
"product_qty": [
{
"quantity_id": "3",
"quantity_name": "500 gm",
"value": "500",
"quantity_status": "1"
},
{
"quantity_id": "4",
"quantity_name": "1 Kg",
"value": "1000",
"quantity_status": "1"
}
In this "msg" which is an array and contains value in form of object but "product_qty" again an array which is under the object,now how can i fetch the elements value of product_qty ]1
just used this
if([array containsObject dict])
{
already in your array
}
else
{
not in your array
}
Updated Code:
NSDictionary *mainDic = [arrResponse objectAtIndex:0];
NSArray *arrMsg = [mainDic valueForKey:#"msg"];
for (NSDictionary *dicSub in arrMsg) {
NSArray *arrProdQuality = [dicSub valueForKey:#"product_qty"];
for (NSDictionary *dicQuality in arrProdQuality) {
NSLog(#"quantity_name %#",[dicQuality valueForKey:#"quantity_name"]);
}
}
You need to fetch key value like this:
NSDictionary *dictProducts = array[0]; // From Main Array.
NSArray *allProduct = dictProducts[#"msg"]; // Form Dictionary.
NSDictionary *firstProduct = allProduct[0];
NSLog(#"Product Qty : %#", firstProduct[#"product_qty"]); // Here you can get product_qty array.
Hope this will helps.

ObjC How to display same JSON records based on their key in a single UITableViewCell

The JSON from the backend is the following
"data": [
{
"id": 108,
"userId": "84945dd7-4ebe-418a-b5ec-bd418d226778",
"notificationType": 0,
"messagingService": 1,
"status": 2
},
{
"id": 109,
"userId": "84945dd7-4ebe-418a-b5ec-bd418d226778",
"notificationType": 0,
"messagingService": 2,
"status": 2
},
{
"id": 110,
"userId": "84945dd7-4ebe-418a-b5ec-bd418d226778",
"notificationType": 1,
"messagingService": 1,
"status": 2
},
{
"id": 111,
"userId": "84945dd7-4ebe-418a-b5ec-bd418d226778",
"notificationType": 1,
"messagingService": 3,
"status": 2
}
]
I fetch the records to an Array from the backend
#property(nonatomic, strong)NSArray *userPreferences;
What I want to succeed is to display those records with the same key "notificationType" in a single cell to present the different types of the other key "messagingService". And finally to tap on any indexPath.row and know which record I have choose and do my active/inactive option.
thank you for the message Jordan Bonitatisfor, based on your example this is what i came up with :
NSMutableDictionary *resultDict = [NSMutableDictionary dictionary];
for (int i = 0; i < [preferences count]; i++)
{
if (resultDict[[preferences[i] valueForKey:#"notificationType"]]) {
//pull out the array and add to it
NSMutableArray *mutableArray = [[NSMutableArray alloc]initWithArray: resultDict[[preferences[i] valueForKey:#"notificationType" ]]];
[mutableArray addObject:preferences[i]];
[resultDict setValue:mutableArray forKey:[preferences[i] valueForKey:#"notificationType" ] ];
}
else
{
NSArray *array = #[preferences[i]];
[resultDict setValue:array forKey:[preferences[i] valueForKey:#"notificationType" ] ];
}
}
[self.foundPreferences addObject:resultDict];
How can i append the resultDict now to the proper cell .
After hard testing and trial and errors i managed to succeed to exactly what i want with the help of Generics (never used them before) thx for all the help.
NSMutableDictionary<NSNumber*, NSMutableDictionary<NSNumber *, KYNotificationPreference *> *> *preferences = [NSMutableDictionary new];
for(NSDictionary *rawPreference in (*response).data){
KYNotificationPreference *preference = [KYDeserializer notificationPreferenceFromSerializedObject:rawPreference];
NSMutableDictionary *notificationTypeDictionary = preferences[#(preference.notificationType)];
if(!notificationTypeDictionary){
notificationTypeDictionary = [NSMutableDictionary new];
[preferences setObject:notificationTypeDictionary forKey:#(preference.notificationType)];
}
[notificationTypeDictionary setObject:preference forKey:#(preference.messagingService)];
}

Parsing JSON and get the values [duplicate]

I have the following JSON:
{
"meta": {
"code": 200
},
"response": {
"deals": [
{
"id": 32373,
"date_added": "2011-01-13 12:12:50",
"end_date": "2011-01-14 10:00:00",
"active": 1,
"discount": {
"raw": 71,
"formatted": "71%"
},
"price": {
"raw": "85.00",
"formatted": "$85"
},
"value": {
"raw": "300.00",
"formatted": "$300"
},
"purchased": 82,
"left": null,
"title": "$85 For $300 Babyface Facial At Park Avenue MedSpa",
"yipit_title": "71% off Babyface Facial",
"url": "http://yipit.com/aff/click/?deal=AvwTADtE&key=F374EFbM",
"yipit_url": "http://yipit.com/new-york/livingsocial/85-for-300-babyface-facial-at-park-avenue-medspa/",
"images": {
"image_big": "http://d22nv2k05ynu7x.cloudfront.net/deal_images/deal/85-for-300-babyface-facial-at-park-avenue-medspa-1294920769_display_image.jpg",
"image_small": "http://d22nv2k05ynu7x.cloudfront.net/deal_images/deal/85-for-300-babyface-facial-at-park-avenue-medspa-1294920769_small_image.jpg"
},
"division": {
"slug": "new-york",
"name": "New York",
"active": 1,
"time_zone_diff": -4,
"lat": "40.7142690000000000",
"lon": "-74.0059730000000000",
"url": "http://yipit.com/new-york/"
},
"tags": [
{
"name": "Facial",
"slug": "facial",
"url": "http://yipit.com/new-york/deals/facial/"
},
{
"name": "Spa",
"slug": "spa",
"url": "http://yipit.com/new-york/deals/spa/"
}
],
"business": {
"name": "Park Avenue MedSpa",
"url": "",
"locations": [
{
"address": "565 Park Ave",
"locality": "New York",
"phone": "212-593-8821",
"lat": null,
"lon": null
}
]
},
"source": {
"name": "LivingSocial",
"slug": "livingsocial",
"paid": 0,
"url": "http://yipit.com/new-york/livingsocial"
}
}
]
}
}
Here is how I am parsing it:
NSArray *deals = [[results objectForKey:#"response"] valueForKey:#"deals"];
NSLog(#"%#",[[results objectForKey:#"response"] valueForKey:#"deals"]);
for(NSDictionary* deal in deals)
{
NSLog(#"Title: %#", [deal valueForKey:#"title"]);
NSLog(#"URL: %#", [deal valueForKey:#"url"]);
NSLog(#"Value: %#", [[deal valueForKey:#"value"] valueForKey:#"formatted"]);
NSLog(#"Picture URL: %#", [[deal valueForKey:#"images"] valueForKey:#"image_small"]);
NSLog(#"Business: %#", [[deal valueForKey:#"business"] valueForKey:#"name"]);
NSLog(#"Address: %#", [[[deal valueForKey:#"business"] valueForKey:#"locations"] valueForKey:#"address"]);
NSLog(#"City: %#", [[[deal valueForKey:#"business"] valueForKey:#"locations"] valueForKey:#"locality"]);
NSLog(#"Phone: %#", [[[deal valueForKey:#"business"] valueForKey:#"locations"] valueForKey:#"phone"]);
[items addObject:deal];
}
My logging looks good except for Address, City and Phone. Here is the log:
Title: $10 for $20 Worth of Food and Drinks at Blondies in Tempe
URL: http://yipit.com/aff/click/?deal=cHBPNZ3w&key=93HU7t2d
Value: $20
Picture URL: http://d22nv2k05ynu7x.cloudfront.net/deal_images/deal/50-off-at-blondies-sports-bar-1298454745_small_image.jpg
Business: Blondies Sports Bar
Address: (
"501 S Mill Ave"
)
City: (
Tempe
)
Phone: (
"702-737-0444"
)
From the JSON you provided, locations is an array (that's what the square brackets mean), so the values that are returned from valueForKey: are contained in NSArray instances (hence the parentheses).
You could use objectAtIndex: before the last call to valueForKey: to obtain just the value you're looking for.
By the way, you can also use valueForKeyPath: to simplify accessing nested values, for example
[deal valueForKeyPath:#"business.name"];
[[deal valueForKey:#"business"] valueForKey:#"locations"] returns an array. Calling -valueForKey: on an NSArray executes valueForKey: for every object in the array and returns an array of the results (see the NSArray documentation for this). So that's what you get, an array of the corresponding values.
You could try changing your code to something like this:
NSDictionary *primaryLocation = [[[deal valueForKey:#"business"] valueForKey:#"locations"] objectAtIndex:0];
NSLog(#"Address: %#", [primaryLocation valueForKey:#"address"]);
NSLog(#"City: %#", [primaryLocation valueForKey:#"locality"]);
NSLog(#"Phone: %#", [primaryLocation valueForKey:#"phone"]);

addObject in Array like xml structure

Folks,
I have a Array similar to oneArray bellow, this file is already ready and functional. I want to mount this array dynamic, like addObject, but how can I add a descs value and into it test values ?
Tks for help.
#property (strong, nonatomic) NSArray *oneArray;
self.oneArray = #[ #{ #"desc": #"desc1",
#"descs": #[ #{ #"test": #"test1" },
#{ #"test": #"test2" }
]
},
#{ #"desc": #"desc2",
#"descs": #[ #{ #"test": #"test3" },
#{ #"test": #"test4" },
#{ #"test": #"test5" }
]
}
];
NSArray can't have Associative name. If you want to have associative name better use NSDictionary.
You can use for this purpose json structure and NSJSONSerialization, e.g. file content would be
[
{
"desc": "desc1",
"descs": [
{
"test": "test1"
},
{
"test": "test2"
}
]
},
{
"desc": "desc2",
"descs": [
{
"test": "test3"
},
{
"test": "test4"
},
{
"test": "test5"
}
]
}
]
And code:
NSError *error;
NSData *contentFile = [NSData dataWithContentsOfFile:#"my.json"];
NSArray *descs = [NSJSONSerialization JSONObjectWithData:contentFile options:kNilOptions error:&error];

How to filter a multi-dimensional array

I have the following multi-dimensional array (stripped and reduced for clarity)
[
{
"type": "type1",
"docs": [
{
"language": "EN"
},
{
"language": "DE"
},
{
"language": "EN"
}
]
},
{
"type": "type2",
"docs": [
{
"language": "EN"
}
]
},
{
"type": "type3",
"docs": [
{
"language": "FR"
},
{
"language": "DE"
},
{
"language": "DE"
}
]
}
]
I want to filter it, so only docs objects with a language of DE are shown. In other words, I need this:
[
{
"type": "type1",
"docs": [
{
"language": "DE"
}
]
},
{
"type": "type2",
"docs": []
},
{
"type": "type3",
"docs": [
{
"language": "DE"
},
{
"language": "DE"
}
]
}
]
My array is initially created by the following piece of code:
NSMutableArray *docsArray;
[self setDocsArray:[downloadedDocsArray mutableCopy]];
I have tried looping the array and removing unwanted objects. I have tried looping the array and copying wanted objects to a new array. I have tried using NSPredicate instead of looping, all of which had very little success.
Can anyone point me in the right direction?
Thanks in advance.
You should iterate over the array to get the dictionaries containing the arrays to filter:
NSArray* results;
NSMutableArray* filteredResults= [NSMutableArray new]; // This will store the filtered items
// Here you should have already initialised it
for( NSDictionary* dict in results)
{
NSMutableDictionary* mutableDict=[dict mutableCopy];
NSArray* docs= dict[#"docs"];
NSPredicate* predicate= [NSPredicate predicateWithFormat: #"language like 'DE'"];
docs= [docs filteredArrayUsingPredicate: predicate];
[mutableDict setObject: docs forKey: #"docs"];
[filteredResults addObject: mutableDict];
}