call for nested json objects, in ios - ios

I'm working on a ios project. I used AFNetworking to call json.
I just want to call for an specific json object. that meant for an specific nested json object.please help me to do that. as an example this is my json feed. In here I want to call for only first url inside thumbnail.
{ status:"ok",
count:50,
count_total:44444,
pates:333,
- posts:[
- {
id:3333,
type:"post",
- thumbnail_images :{
- full : {
url:"",
width:666
},
-thumbnail:{
url:"",
width:333
},
- large:{
url:"",
width:777
}
}
},
- {
id:3334,
type:"post",
- thumbnail_images :{
- full : {
url:"",
width:6644
},
-thumbnail:{
url:"",
width:3345
},
- large:{
url:"",
width:7778
}
}
},
- {
id:333344,
type:"post",
- thumbnail_images :{
- full : {
url:"",
width:6665
},
-thumbnail:{
url:"",
width:3336
},
- large:{
url:"",
width:7770
}
}
},
]
}
and also this is my objective-C method.
- (void)loadImagesToCategoryone
{
imagespost = nil;
NSString *urlOne = [NSString stringWithFormat:#"some url"];
AFHTTPRequestOperationManager *managerone = [AFHTTPRequestOperationManager manager];
[managerone GET:urlOne parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
imagesposts = (NSDictionary *)responseObject;
NSArray *resultone = [imagesposts objectForKey:#"posts"];
imagespost = [NSMutableArray array];
for (NSDictionary *imageone in resultone)
{
Categories *categoryone = [Categories new];
NSArray *firstArray = [imageone objectForKey:#"thumbnail_images"];
NSLog(#"%#",firstArray[0]);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
}

note that the thumbnail_images is a Dictionary not an Array.
NSArray *resultone = [imagesposts objectForKey:#"posts"];
if ([resultone count]) {
//If need thumbnail of first post only then
NSDictionary *firstPost = resultone[0];
Categories *categoryone = [Categories new];
NSDictionary *imageDetails = [imageone objectForKey:#"thumbnail_images"];
NSDictionary *thumbnailImage = [imageDetails objectForKey:#"thumbnail"];
NSString *urlString = [thumbnailImage objectForKey:#"url"];
//Assume thumbnail image is required
NSLog(#"%#",urlString);
}

Related

Handle object of different types

From my backend API, I get a json of objects consisting of array, dictionary, number, bool, string etc. For eg.
{
data:[
{
id : 1,
name : "abcd"
},
{
id : 2,
name : "abcde"
},
{
id : 3,
name : "abcde"
},
]
total_count : 10
}
Sometimes the value in total_count comes as a number and sometimes it comes as a string. In my code I have coded
[lbl setText:[jsonObject valueForKey:#"total_count"]]
This crashes because when the total_count key value is a number. Obviously I can do this
[lbl setText:[NSString stringWithFormat:#"%d",[[jsonObject valueForKey:#"total_count"] intValue]]];
but this happens at a lot of places in the API. A string is coming instead of a bool.
data:false instead of data:[]
[EDIT]
[[AFHTTPRequestOperationManager manager] GET:[URLString attachToken] parameters:parameters success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {
if([[[responseObject valueForKey:#"response"] valueForKey:#"status"] boolValue]) {
NSLog(#"success");
}
if(success)success(operation, **responseObject**);
} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
if(failure)failure(operation, error);
if(operation.response.statusCode == 0) {
ATAFNetworkingRequestObject *obj = [[ATAFNetworkingRequestObject alloc] init];
obj.urlString = URLString;
obj.paramters = parameters;
obj.successBlock = success;
obj.failureBlock = failure;
obj.type = ATNetworkingRequestGET;
if(![self duplicateRequestExists:obj])[pendingAPICalls addObject:obj];
}
[self logAPIFailedWithOperation:operation parameters:parameters error:error];
} autoRetry:5 retryInterval:7];
do like after serilization based on your A string is coming instead of a bool. data:false instead of data:[]
if([datajsonObject isKindOfClass:[NSArray class]]){
//Is array
}else if([datajsonObject isKindOfClass:[NSDictionary class]]){
//is dictionary
}else if([datajsonObject isKindOfClass:[NSString class]])
{
//is String
}
else{
//is something else
}
You can check server value is Number or string as this
NSString *newString = [NSString stringWithFormat:#"%#",[[jsonObject valueForKey:#"total_count"]
if ([newString isKindOfClass:[NSNumber class]])
{
NSLog(#"It is number");
}
if ([newString isKindOfClass:[NSString class]])
{
NSLog(#"It is string");
}
Swift code :
lblCount.text = String(datajsonObject["total_count"] as AnyObject)
Objective c :
NSString *strCount = [NSString stringWithFormat:#"%#",[jsonObject valueForKey:#"total_count"]]
if ([strCount isKindOfClass:[NSString class]])
{
// Write your code to show on label
}

how to remove duplicates from array of dictionary for a specific key

{
distance = "0.03159804520191554";
rid = 374824705969;
uuid = "1838346268_374823983610_2016-08-08T07:32:08.679GMT";
},
{
rid = 374824705969;
uuid = "1838346268_374823983610_2016-08-08T07:32:08.679GMT";
},
{
rid = 374824706065;
uuid = "1838346268_374823983610_2016-08-08T07:32:22.680GMT";
}
This is what I got from the array of dictionaries. I want to remove duplicates where rid=374824705969 without using loops.Can any one help me.
Thanks in advance.
Try these one:
NSArray *array = #[
#{
#"rid" : #374824705969,
#"uuid" : #"1838346268_374823983610_2016-08-08T07:32:08.679GMT"
},
#{
#"rid" : #374824705969,
#"uuid" : #"1838346268_374823983610_2016-08-08T07:32:08.679GMT"
},
#{
#"rid" : #374824706065,
#"uuid" : #"1838346268_374823983610_2016-08-08T07:32:22.680GMT"
}];
NSMutableSet *keys = [NSMutableSet new];
NSMutableArray *result = [NSMutableArray new];
for (NSDictionary *data in array) {
NSString *key = data[#"rid"];
if ([keys containsObject:key]) {
continue;
}
[keys addObject:key];
[result addObject:data];
}
NSLog(#"%#", result);

Load json in UITableview Objective c

I want to display my json file from a server in a UITableview. I have the part where i get the json from the web but i don't know how to put it in a table. Can somebody help me with some tips.
Here is my Json
{ "Food": [ { "title": "Botherham", "speaker": "Jason Shapiro" }, { "title": "Ei", "speaker": "Jim White" } ], "IDK NOTHING": [ { "title": "Botherham" }, { "title": "Ei" } ] }
And here is my objective code of how i get my json from the web
#import "ViewControllerLogin.h"
#implementation ViewControllerLogin
#synthesize userName;
- (void)viewDidLoad {
[super viewDidLoad];
[self.navigationItem setHidesBackButton:YES];
self.title = userName;
NSData *allCoursesData = [[NSData alloc] initWithContentsOfURL:
[NSURL URLWithString:#"http://192.168.1.11:8888/swift/asortiment.php"]];
NSError *error;
NSMutableDictionary *allCourses = [NSJSONSerialization
JSONObjectWithData:allCoursesData
options:NSJSONReadingMutableContainers
error:&error];
if( error )
{
NSLog(#"%#", [error localizedDescription]);
}
else {
NSArray *Food = allCourses[#"Food"];
for ( NSDictionary *theCourse in Food )
{
NSLog(#"Title: %#", theCourse[#"title"] );
NSLog(#"----");
}
}
}
#end

Parsing JSON to an object

I'm trying to parse this JSON:
{
"GetMachineGroupsResult": {
"MachineGroups": [
{
"GroupCount": 1,
"GroupID": 101,
"GroupName": "Machine11"
},
{
"GroupCount": 6,
"GroupID": 201,
"GroupName": "Machine12"
},
{
"GroupCount": 1,
"GroupID": 301,
"GroupName": "Machine13"
},
{
"GroupCount": 1,
"GroupID": 501,
"GroupName": "Machine14"
},
{
"GroupCount": 7,
"GroupID": 701,
"GroupName": "Machine15"
},
{
"GroupCount": 1,
"GroupID": 901,
"GroupName": "Machine16"
},
{
"GroupCount": 1,
"GroupID": 1001,
"GroupName": "Machine17"
}
],
"Status": 0
}
}
Into an object created with attributes GroupCount, GroupID and GroupName.
Here is my code:
if (request.responseStatusCode >= 200 && request.responseStatusCode < 300)
{
NSData *responseData = [request responseData];
NSError* error;
NSDictionary* jsonOverview = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSString *resultStatusString = jsonOverview[#"GetMachineOverviewResult"][#"Status"];
int resultStatus = [resultStatusString intValue];
NSDictionary *parsedObject = jsonOverview[#"GetMachineGroupsResult"];
NSMutableArray *groups = [[NSMutableArray alloc] init];
NSArray *results = [parsedObject valueForKey:#"MachineGroups"];
NSLog(#"Count %lu", (unsigned long)results.count); //results.count = 7
for (NSDictionary *parseDic in results) {
MachineGroupList *machinegrouplist = [[MachineGroupList alloc] init];
NSLog(#"%#", [parseDic class]);
NSLog(#"%#", parseDic);
for (NSString *key in parseDic) {
if ([machinegrouplist respondsToSelector:NSSelectorFromString(key)]) {
[machinegrouplist setValue:[parseDic valueForKey:key] forKey:key];
}
[groups addObject:machinegrouplist];
}
}
NSLog (#"GroupObjects %lu", (unsigned long)[groups count]); //groups count = 21
For some reason, which I cannot fathom, it parses each item three times and I end up with 21 objects instead of 7. I know it will be something simple for one of the experts here but I am new to all this and would really appreciate a helping hand here, thanks.
Edit:
Thanks a lot, here is how it now looks and it works.. The addobject was in the wrong section!
for (NSDictionary *parseDic in results)
{
MachineGroupList *machinegrouplist = [[MachineGroupList alloc] init];
NSLog(#"%#", [parseDic class]);
NSLog(#"%#", parseDic);
for (NSString *key in parseDic)
{
if ([machinegrouplist respondsToSelector:NSSelectorFromString(key)])
{
[machinegrouplist setValue:[parseDic valueForKey:key] forKey:key];
}
//[groups addObject:machinegrouplist];
}
[groups addObject:machinegrouplist];
}
NSLog (#"GroupObjects %lu", (unsigned long)[groups count]); //groups count = 7
What's happening is the following. First, lets comment out some of the last lines of code so that it looks like this:
for (NSDictionary *parseDic in results) {
//MachineGroupList *machinegrouplist = [[MachineGroupList alloc] init];
NSLog(#"%#", [parseDic class]);
//NSLog(#"%#", parseDic);
//for (NSString *key in parseDic) {
// if ([machinegrouplist respondsToSelector:NSSelectorFromString(key)]) {
// [machinegrouplist setValue:[parseDic valueForKey:key] forKey:key];
// }
// [groups addObject:machinegrouplist];
//}
}
//NSLog (#"GroupObjects %lu", (unsigned long)[groups count]); //groups count = 21
You'll se that you're iterating over 7 dictionaries, each of which has 3 objects.
Now, comment out the previous NSLog, uncomment the the inner for loop and add a NSLog inside that loop to see what you're iterating on.
for (NSDictionary *parseDic in results) {
//MachineGroupList *machinegrouplist = [[MachineGroupList alloc] init];
//NSLog(#"%#", [parseDic class]);
//NSLog(#"%#", parseDic);
for (NSString *key in parseDic) {
// if ([machinegrouplist respondsToSelector:NSSelectorFromString(key)]) {
// [machinegrouplist setValue:[parseDic valueForKey:key] forKey:key];
// }
// [groups addObject:machinegrouplist];
NSLog(#"key: %#", key);
}
}
//NSLog (#"GroupObjects %lu", (unsigned long)[groups count]); //groups count = 21
You are iterating over the 3 objects of each of the 7 dictionaries and since you're adding each object to groups outside of if ([machinegrouplist respondsToSelector:NSSelectorFromString(key)]) you end up adding 21 to groups
Cheers.

Parsing JSON hierarchy

I'm still trying (I already asked a few question about this) to parse my own JSON file. Here is my JSON :
{
"album":[
{
"album_titre":"Publicité",
"album_photo":"blabla.jpg",
"album_videos":[
{
"titre_video":"Chauffage Compris",
"duree_video":"01'25''",
"photo_video":"chauffage.jpg",
"lien_video":"www.bkjas.jhas.kajs"
},
{
"titre_video":"NIFFF 2012",
"duree_video":"01'43''",
"photo_video":"nifff.jpg",
"lien_video":"www.bkjas.jhas.kajs"
}
]
},
{
"album_titre":"Events",
"album_photo":"bloublou.jpg",
"album_videos":[
{
"titre_video":"Auvernier Jazz",
"duree_video":"01'15''",
"photo_video":"auvernier.jpg",
"lien_video":"www.bkjas.jhas.kajs"
},
{
"titre_video":"NIFFF 2011",
"duree_video":"01'03''",
"photo_video":"nifff2011.jpg",
"lien_video":"www.bkjas.jhas.kajs"
}
]
}
]
}
With help of community, I've made this :
- (void) viewDidLoad
{
[super viewDidLoad];
dispatch_async (kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:lienAlbumsVideo];
[self performSelectorOnMainThread:#selector(fetchedData:)withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary *document = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if (document==nil)
{
NSLog( #"oops\n%#", error);
}
NSArray *album = document[#"album"];
NSMutableArray *album_titre = [NSMutableArray new];
NSMutableArray *album_photo = [NSMutableArray new];
NSMutableArray *album_videos = [NSMutableArray new];
for( NSDictionary *elementOnRoot in album )
{
[album_titre addObject:elementOnRoot[#"album_titre"]];
[album_photo addObject:elementOnRoot[#"album_photo"]];
[album_videos addObject:elementOnRoot[#"album_videos"]];
}
NSLog(#"%#", [album_titre objectAtIndex:0]);
NSLog(#"%#", [album_videos objectAtIndex:1]);
NSLog(#"%#", album_photo);
}
Now, I'm a bit mixed up with structure. My question is how (using my actual Xcode) can I have a list (NSArray or dictionary) of "titre_video", "duree_video", "photo_video" and "lien_video"?
Thank you for your help and sorry for my basic xcode level...
Nicolas
for( NSDictionary *albumDic in album )
{
for( NSDictionary *album_videosDic in albumDic[#"album_videos"])
{
[album_titre addObject:album_videosDic[#"titre_video"]];
[album_videos addObject:album_videosDic[#"duree_video"]];
[album_photo addObject:album_videosDic[#"photo_video"]];
}
}

Resources