How to Arrange JSON Parsed Array Based On Page Number? - ios

i am newbie in iOS Development i parsed my JSON Data my Data like as
{
mid: "1",
name: "august 2014",
front_image:"http://www.truemanindiamagazine.com/webservice/magazineimage/frontimage/1.jpg",
title: "August fist edition",
release_date: "2014-08-01",
short_description: "Here we present to you for the first time our Magazine Trueman India. “Trueman India” covers Bollywood Gossips, film reviews, upcoming movies, F",
current_issue: 0,
-demopage: [
{
link:my image URL
page_no: "1"
},
{
link: my image URL,
page_no: "16"
},
{
link: my image URL,
page_no: "2"
},
{
link: my image URL,
page_no: "22"
},
{
link: my image URL,
page_no: "25"
},
{
link: my image URL,
page_no: "26"
},
And i parsed this Data into two array like as
NSError* error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
self.imagesa= nil;
if([jsonDict count]>0)
{
NSArray *arrData = [jsonDict objectForKey:#"data"];
if([arrData count]>0)
{
NSDictionary *imgDict = [arrData objectAtIndex:1];
if([imgDict count]>0)
{
NSMutableArray *imgsLinkArray = [imgDict objectForKey:#"demopage"];
self.imagesa = imgsLinkArray;
}
}
}
then it is Parsed and i got aresult what i want but here one problem is taht when i Show this image with Page number in Scrollview then i Show my image in to as per i got JSON data but i want my Imageview are Based on PageNumber like as From 1 to upto the data array Size.please Give me Solution for that i arrange my Image Based on my page number Wise here my Code for image and Page Number Parsing is
for(int index=0; index < [self.imagesa count]; index++)
{
NSDictionary *dict=[self.imagesa objectAtIndex:index];
NSString *image=[dict valueForKey:#"link"];
NSString *pageNumber=[dict valueForKey:#"page_no"];
smallImage = [[UIImageView alloc] init];
pageLabel=[[UILabel alloc]init];
[pageLabel setBackgroundColor:[UIColor clearColor]];
[smallImage sd_setImageWithURL:[NSURL URLWithString:image] placeholderImage:[UIImage imageNamed:#"1.png"]];
[pageLabel setText:[NSString stringWithFormat:#"Page%#",pageNumber]];
and i added my label and imageview into my Scrollview then it is Working as i want but it is not Show image Based on Page nuber like as From ! to upto array size please Give me Solution for that.

Sort your imagesLinkArray this way:
self.imagesa = [[imgsLinkArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1[#"page_no"] intValue] > [obj2[#"page_no"] intValue]) {
return NSOrderedDescending;
} else if ([obj1[#"page_no"] intValue] < [obj2[#"page_no"] intValue]) {
return NSOrderedAscending;
}
return NSOrderedSame;
}] mutableCopy];

You should set the pageLabel test based on your index variable (+1), not the pageNumber. As follows:
[pageLabel setText:[NSString stringWithFormat:#"Page %lu",(long unsigned)(index+1)]];

Bro you drop value in An array Like this
if([imgDict count]>0)
{
NSMutableArray *imgsLinkArray = [imgDict objectForKey:#"demopage"];
self.imagesa = imgsLinkArray;
}
Then you have all the value in self.imagesa array....
So just wright only this....
[pageLabel setText:[NSString stringWithFormat:#"Page %lu",(long unsigned)[[self.imagesa objectAtIndex:index] valueForKey:#"page_no"]]];
For your short array OrderBy ............
NSMutableArray *recent=[[NSMutableArray alloc]init];
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"page_no" ascending:YES selector:#selector(localizedStandardCompare:)] ;
[self.imagesa sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
recent = [[self.imagesa sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]] copy];
self.imagesa = (NSMutableArray *) [[NSMutableArray alloc]initWithArray:recent];

Related

Efficiently looping the jsonarray containing month and date that are of optional values

I have got the following json array. I want to concatenate statutory month (in terms of words )and add them into data base.
Sometimes months and date may not be present. Sometimes date will be present and months wont be present and vice versa. I have to handle this conditions and make store the date and month like 31 January,30April etc into the db.
[
{
"statutory_month": 1,
"statutory_date": 31
},
{
"statutory_month": 4,
"statutory_date": 30
},
{
"statutory_month": 7,
"statutory_date": 31
},
{
"statutory_month": 10,
"statutory_date": 31
}
]
Is there an efficient way to handle this situation without doing lots of loops?
Have you try this first create one months array. After that extract data from dictionary like this
NSArray *months = [[NSArray alloc] initWithObjects:#"Jan", #"Feb", #"Mar", #"Apr", #"May", #"Jun", #"July", #"Aug", #"Sept", #"Oct", #"Nov", #"Dec", nil];
NSArray *resultDate = [[NSArray alloc] init];
for (NSDictionary *dic in jsonArr) //jsonArr is your response arr
{
if([dic objectForKey:"statutory_month"] && [dic objectForKey:"statutory_date"]) {
NSString *dateObj = [NSString stringWithFormat:#"%d %#",[dic objectForKey:#"statutory_date"], [months objectAtIndex:[dic objectForKey:"statutory_month"]]];
}
else if([dic objectForKey:"statutory_date"]) {
NSString *dateObj = [NSString stringWithFormat:#"%d",[dic objectForKey:#"statutory_date"]];
}
else if([dic objectForKey:"statutory_month"]) {
NSString *dateObj = [NSString stringWithFormat:#"%#",[months objectAtIndex:[dic objectForKey:"statutory_month"]]];
}
else {
NSString *dateObj = #"No date";
}
[resultDate addObject:dateObj];
}
Hope this will help you.
You can take one array of Response:
NSArray *arr = //response;
for (NSDictionary *dic in arr)
{
if([dic objectForKey:"statutory_month"])
//add
if([dic objectForKey:"statutory_date"])
//add
}
P.S I didn't try it my self. But Hope it will Help you.

IOS Compare two array and get Result

I have below JSON Format:
{
"Get_your_story_answer": [
{
"st_id": "19",
"story_title": "Newone",
"user_fb_id": "1649424812005217",
"winner_fb_id": "1685417121693688",
"winner_fb_id2": "",
"winner_fb_id3": "",
"story": "\ud83d\ude33\ud83d\ude25\ud83d\ude14\ud83d\ude0c",
"status": "1",
"s_created_date": "2016-01-18 23:06:05",
"reply_answer": [
{
"l_id": "42",
"story_id": "19",
"user_fb_id": "1649424812005217",
"selected_user_fb_id": "1685417121693688",
"answer": "hahaha",
"l_rating": "0",
"status": "1",
"l_created_date": "2016-01-18 23:10:51",
"l_new_created_date": "2016-01-19 11:40:51",
"winner": "1",
"answer_user_id": "3",
"answer_fb_id": "1685417121693688",
"answer_user_name": "Kin Patty"
},
{
"l_id": "43",
"story_id": "19",
"user_fb_id": "1649424812005217",
"selected_user_fb_id": "1498304680499454",
"answer": "",
"l_rating": "0",
"status": "1",
"l_created_date": "2016-01-18 23:06:05",
"l_new_created_date": "2016-01-19 11:36:05",
"winner": "0",
"answer_user_id": "10",
"answer_fb_id": "1498304680499454",
"answer_user_name": "John Kingman"
}
]
}
],
"status": "1",
"msg": "Get data"
}
Now I have to get Winner id
for Example "winner_fb_id" from [Get_your_story_answer] and compare it with [reply_answer].
If [reply_answer] contain "winner_fb_id" then I have to take only that name as winner .
Like in my Example , "Kin Patty"
I have tried this ,
//_getwind is mutable array
_getwinnerid =[NSMutableArray new];
_getwinnerid=[[_dataDictionary valueForKey:#"Get_your_story_answer"]valueForKey:#"winner_fb_id"];
Here is _getwinnerid output
<__NSArrayI 0x7ffb5a57c7b0>(
1685417121693688
NSArray *replaydata=[[_dataDictionary valueForKey:#"Get_your_story_answer"]valueForKey:#"reply_answer"];
Here is Replay Data Result
if (![replaydata containsObject:_getwinnerid]) {
NSLog(#"data");
}
Note:- Winner Id will be multiple. so, I have to compare 2 or more winner id and then take name from replay data response. And then I have to set name of winner in UITableview.
The value of Get_your_story_answer is an array, the requested data is in the first item of the array
NSDictionary *getYourStoryAnswer = _dataDictionary[#"Get_your_story_answer"][0];
Now get the winner ID and the array of answers
NSString *winnerID = getYourStoryAnswer[#"winner_fb_id"];
NSArray *answers = getYourStoryAnswer[#"reply_answer"];
Then enumerate the answers array (there are other solutions using blocks etc.)
for (NSDictionary *answer in answers) {
if ([answer[#"answer_fb_id"] isEqualToString: winnerID]) {
NSLog(#"%#", answer[#"answer_user_name"]);
break;
}
}
PS: Never use valueForKey to get one value for a key from a collection type unless you really need (and mean) the KVC method. The designated method is objectForKey or key subscription like above. valueForKey applied to an array returns always an array which is normally not intended.
for this you need to get total winner count from server.
like this.
int winnerCount = 3; //[Get_your_story_answer valueForKey:#"winner_count"];
Hopefully you have a fixed pattern key for winners like winner_fb_id, winner_fb_id1, winner_fb_id2 etc.
This will give you the desired result of winners name in array.
id response; // your response here
NSArray *array = [response objectForKey:#"Get_your_story_answer"];
NSDictionary *Get_your_story_answer = array[0];
NSMutableArray *winnersArray = [[NSMutableArray alloc] init];
int winnerCount = 3; //[Get_your_story_answer valueForKey:#"winner_count"];
for (int i = 0; i< winnerCount; i++) {
NSString *winnerId = nil;
if(i != 0){
winnerId = [Get_your_story_answer valueForKey:[NSString stringWithFormat:#"winner_fb_id%d",i]];
}
else{
winnerId= [Get_your_story_answer valueForKey:[NSString stringWithFormat:#"winner_fb_id"]];
}
if(winnerId)
{
[winnersArray addObject:winnerId];
}
}
__block NSMutableArray *resultArray = [[NSMutableArray alloc] init];
NSArray *replyAnswers = [Get_your_story_answer objectForKey:#"reply_answer"];
[replyAnswers enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
NSString *answer_fb_id = [obj valueForKey:#"answer_fb_id"];
[winnersArray enumerateObjectsUsingBlock: ^(NSString * winnerId, NSUInteger idx, BOOL *stop) {
if([winnerId isEqualToString:answer_fb_id]){
// get name of winner
[resultArray addObject:[obj valueForKey:#"answer_user_name"]];
}
}];
}];
// Your name of wiiners are in resultArray.
I have filtered array using the answer as said by larme Thank you.
NSError *errorJSON = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&errorJSON];
if (!errorJSON)
{
NSDictionary *storyAnwser = [json[#"Get_your_story_answer"] firstObject];
NSArray *allAnswersKeys = [storyAnwser allKeys];
NSArray *allWinnersKeys = [allAnswersKeys filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSString * _Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
return [evaluatedObject hasPrefix:#"winner_fb_id"];
}]];
NSLog(#"AllWinnersKeys: %#", allWinnersKeys);
NSArray *allWinnersIds = [storyAnwser objectsForKeys:allWinnersKeys notFoundMarker:[NSNull null]];
NSLog(#"AllWinnersIds: %#", allWinnersIds);
NSArray *allAnswers = storyAnwser[#"reply_answer"];
NSLog(#"AllAnswers: %#", allAnswers);
NSArray *allWinners = [allAnswers filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"answer_fb_id IN %#", allWinnersIds]];
NSLog(#"allWinners: %#", allWinners);
NSArray *allWinersNames = [allWinners valueForKey:#"answer_user_name"];
NSLog(#"AllWinnersNames: %#", allWinersNames);
}
else
{
NSLog(#"Error JSON: %#", errorJSON);
}

how to search and replace in NSDictionary?

I have a JSON that I converted into NSDictionary and now I want to search and replace some values in it but I have no idea how to to this,
{
"CODE":200,
"APICODERESULT":"USER_INTERESTS",
"MESSAGE":"user interests fetched successfully",
"VALUE":{
"Books":[
{
"key":"7",
"value":"Fiction",
"selected":true
},
{
"key":"8",
"value":"Romantic",
"selected":true
}
],
"Music":[
{
"key":"11",
"value":"Classical",
"selected":false
},
{
"key":"12",
"value":"Jazz",
"selected":false
},
{
"key":"10",
"value":"Pop",
"selected":false
},
{
"key":"13",
"value":"Western",
"selected":false
}
]
}
}
here I have the value for key that I want to search in the dictionary and when I found that key with the value that I have I want to replace the value for selected in the same block.
For example:-
I have value 10 for key then I want to change the value for key selected to true
so the it will look like this
{
"CODE":200,
"APICODERESULT":"USER_INTERESTS",
"MESSAGE":"user interests fetched successfully",
"VALUE":{
"Books":[
{
"key":"7",
"value":"Fiction",
"selected":true
},
{
"key":"8",
"value":"Romantic",
"selected":true
}
],
"Music":[
{
"key":"11",
"value":"Classical",
"selected":false
},
{
"key":"12",
"value":"Jazz",
"selected":false
},
{
"key":"10",
"value":"Pop",
"selected":true
},
{
"key":"13",
"value":"Western",
"selected":false
}
]
}
}
Consider your input dictionary as mainDictionary and use following code:
NSMutableDictionary *valuesDic = [mainDictionary objectForKey:#"VALUES"];
NSArray *allPossibleKeysArray = [valuesDic allKeys];
for (int j=0; j<allPossibleKeysArray.count; j++) {
NSString *keyStr = [allPossibleKeysArray objectAtIndex:j];
NSArray *array = [valuesDic objectForKey:keyStr];
for (int i=0; i<array.count; i++) {
NSMutableDictionary *dictionary = [array objectAtIndex:i];
NSString *keyString = [NSString stringWithFormat:#"%#",[dictionary objectForKey:#"key"]];
if([keyString isEqualToString:keyvalue]){
[dictionary removeObjectForKey:#"selected"];
[dictionary setObject:[NSNumber numberWithBool:true] forKey:#"selected"];
}
}
}
Hope this helps!!
You should make such changes during parsing the JSON/moving it into model. The code below is a workaround:
NSDictionary *initialJson = //Your JSON here
NSArray *allSubKeys= [initialJson[#"Value"] allKeys];
// Your mutable output.
NSMutableDictionary *mutableJson = [initialJson mutableCopy]
for(NSString *key in allSubKeys) {//Music && Books
// Create another cointainer here
for(NSArray *arr in mutableJson[#"Value][key]) {
// Create another cointainer here
for(NSDictionary *dict in arr) {//key, value, selected
for (NSString *key2 in [dict allKeys]) {
if ([key2 isEqualToString:#"selected"] && [dict[#"value"] equals:#10]) {
// Save YES here
}
else {
// Just copy element
}
// Add object to parent container
}
// Add object to parent container
}
// Add object to parent container
}
// Add object to parent container
}
Here is full solution
NSString* str=#"{\"CODE\":200,\"APICODERESULT\":\"USER_INTERESTS\",\"MESSAGE\":\"user interests fetched successfully\",\"value\":{\"Books\":[{\"key\":\"7\",\"value\":\"Fiction\",\"selected\":true},{\"key\":\"8\",\"value\":\"Romantic\",\"selected\":true}],\"Music\":[{\"key\":\"11\",\"value\":\"Classical\",\"selected\":false},{\"key\":\"12\",\"value\":\"Jazz\",\"selected\":false},{\"key\":\"10\",\"value\":\"Pop\",\"selected\":false},{\"key\":\"13\",\"value\":\"Western\",\"selected\":false}]}}";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"dictionary before updating: %#", dictionary);
// copy old dict
NSMutableDictionary* newDict=[[[NSMutableDictionary alloc]init]autorelease];
[newDict addEntriesFromDictionary:dictionary];
// get the entry to be changed
NSMutableDictionary* valueDict=[[[NSMutableDictionary alloc]init]autorelease];
[valueDict addEntriesFromDictionary:newDict[#"value"]];
NSMutableArray* musicArray=[[[NSMutableArray alloc] init] autorelease];
[musicArray addObjectsFromArray:newDict[#"value"][#"Music"]];
// get the music array and change your property
NSMutableDictionary* musicDict2=[[[NSMutableDictionary alloc] init] autorelease];
[musicDict2 addEntriesFromDictionary:[musicArray objectAtIndex:2]];
[musicDict2 setValue:[NSNumber numberWithBool:YES] forKey:#"selected"];
[musicArray replaceObjectAtIndex:2 withObject:musicDict2];
// update the value dictionary
[valueDict setObject:musicArray forKey:#"Music"];
//update the new dictionary
[newDict setObject:valueDict forKey:#"value"];
NSLog(#"dictionary after updating: %#", newDict);

How to separate contents from NSArray into two new one in Objective C?

any one here have an idea how I could separate this array in to 2??
2013-08-25 02:47:47.052 yahoo[11357:c07] (
"",
"1377253260000.33300.0",
"1377253440000.33280.0",
"1377254100000.33280.0",
"1377255600000.33220.0",
"1377257400000.33220.0",
"1377261660000.33200.0",
"1377264000000.33200.0",
"1377264060000.33200.0",
"1377267780000.33200.0",
"1377271260000.33200.0",
"1377273120000.33200.0",
"1377273180000.33200.0",
"1377273240000.33240.0",
""
)
The first NSArray would be with the long numbers and the second with the smaller one including the ".".
So something like: array1 with 1377253260000 and array2 with 33300.0 and so on.
There are tons of different ways of doing this. For example, you could do something as simple as find the first period, and add the string up to that period in the first array and everything after in the next array:
NSMutableArray *smallerNumbers = [NSMutableArray array];
NSMutableArray *longNumbers = [NSMutableArray array];
for (NSString *string in array) {
NSRange range = [string rangeOfString:#"."];
if (range.location != NSNotFound) {
[longNumbers addObject:[string substringToIndex:range.location - 1]];
[smallerNumbers addObject:[string substringFromIndex:range.location + 1]];
} else {
[longNumbers addObject:#""]; // or you could insert [NSNull null] or whatever
[smallerNumbers addObject:#""];
}
}
Another way..
NSArray *objects = #[
#"",
#"1377253260000.33300.0",
#"1377253440000.33280.0",
#"1377254100000.33280.0",
#"1377255600000.33220.0",
#"1377257400000.33220.0",
#"1377261660000.33200.0",
#"1377264000000.33200.0",
#"1377264060000.33200.0",
#"1377267780000.33200.0",
#"1377271260000.33200.0",
#"1377273120000.33200.0",
#"1377273180000.33200.0",
#"1377273240000.33240.0",
#""
];
NSMutableArray *firstParts = [[NSMutableArray alloc] initWithCapacity:objects.count];
NSMutableArray *secondParts = [[NSMutableArray alloc] initWithCapacity:objects.count];
for (NSString *object in objects)
{
NSArray *components = [object componentsSeparatedByString:#"."];
if (components.count > 0) {
[firstParts addObject:components[0]];
}
if (components.count > 1) {
[secondParts addObject:components[1]];
}
}
NSLog(#"firstParts = %#", firstParts);
NSLog(#"secondParts = %#", secondParts);

How can I get the JSON array data from nsstring or byte in xcode 4.2?

I'm trying to get values from nsdata class and doesn't work.
here is my JSON data.
{
"count": 3,
"item": [{
"id": "1",
"latitude": "37.556811",
"longitude": "126.922015",
"imgUrl": "http://175.211.62.15/sample_res/1.jpg",
"found": false
}, {
"id": "3",
"latitude": "37.556203",
"longitude": "126.922629",
"imgUrl": "http://175.211.62.15/sample_res/3.jpg",
"found": false
}, {
"id": "2",
"latitude": "37.556985",
"longitude": "126.92286",
"imgUrl": "http://175.211.62.15/sample_res/2.jpg",
"found": false
}]
}
and here is my code
-(NSDictionary *)getDataFromItemList
{
NSData *dataBody = [[NSData alloc] initWithBytes:buffer length:sizeof(buffer)];
NSDictionary *iTem = [[NSDictionary alloc]init];
iTem = [NSJSONSerialization JSONObjectWithData:dataBody options:NSJSONReadingMutableContainers error:nil];
NSLog(#"id = %#",[iTem objectForKey:#"id"]);
//for Test
output = [[NSString alloc] initWithBytes:buffer length:rangeHeader.length encoding:NSUTF8StringEncoding];
NSLog(#"%#",output);
return iTem;
}
how can I access every value in the JSON? Please help me.
look like this ..
NSString *jsonString = #"your json";
NSData *JSONdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
if (JSONdata != nil) {
//this you need to know json root is NSDictionary or NSArray , you smaple is NSDictionary
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
if (jsonError == nil) {
//every need check value is null or not , json null like ( "count": null )
if (dic == (NSDictionary *)[NSNull null]) {
return nil;
}
//every property you must know , what type is
if ([dic objectForKey:#"count"] != [NSNull null]) {
[self setCount:[[dic objectForKey:#"count"] integerValue]];
}
if ([dic objectForKey:#"item"] != [NSNull null]) {
NSArray *itemArray = [dic objectForKey:#"item"]; // check null if need
for (NSDictionary *itemDic in itemArray){
NSString *_id = [dic objectForKey:#"id"]; // check null if need
NSNumber *found = (NSNumber *)[dic objectForKey:#"found"];
//.....
//.... just Dictionary get key value
}
}
}
}
I did it by using the framework : http://stig.github.com/json-framework/
It is very powerfull and can do incredible stuff !
Here how I use it to extract an item name from an HTTP request :
(where result is the JSO string)
NSString *result = request.responseString;
jsonArray = (NSArray*)[result JSONValue]; /* Convert the response into an array */
NSDictionary *jsonDict = [jsonArray objectAtIndex:0];
/* grabs information and display them in the labels*/
name = [jsonDict objectForKey:#"wine_name"];
Hope this will be helpfull
Looking at your JSON, you are not querying the right object in the object hierarchy. The top object, which you extract correctly, is an NSDictionary. To get at the items array, and the single items, you have to do this.
NSArray *items = [iTem objectForKey:#"item"];
NSArray *filteredArray = [items filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:#"id = %d", 2];
if (filteredArray.count) NSDictionary *item2 = [filteredArray objectAtIndex:0];
Try JSONKit for this. Is is extremely simple to use.
Note sure if this is still relevant, but in iOS 5, apple added reasonable support for JSON. Check out this blog for a small Tutorial
There is no need to import any JSON framework. (+1 if this answer is relevant)

Resources