Load json in UITableview Objective c - ios

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

Related

iOS Obj-C - How to create NSDictionary from object containing NSArray, but only use specific fields?

I want to create JSON containing a few objects including an NSArray of custom objects (one of which is also an NSArray). For the objects in the NSArray, I only want to save specific fields (some of which are basic C/C++ types - ie. int, bool, etc.).
At the moment I'm using NSKeyedArchiver with the NSArray objects conforming to the NSCoding protocol, where I can save the specific fields (converting the POD's to NSObject's) in the encodeWithCoder method.
An example of the JSON I want to create is as follows (comments show data type in object):
{
"title:"My Title", // NSString
"revision":1, // int
"tasks": [ // NSArray
{ // Is this necessary ?
"task": { // task object
"name": "Task 1", // NSString
"repeat": 1, // int
"sub_tasks": [ // NSArray
{ // Is this necessary ?
"sub_task": { // sub task object
"name":"Do This", // NSString
"repeat":2 // int
},
"sub_task": {
"name":"Do That",
"repeat":2
}
} // Is this necessary ?
]
},
"task": { // task object
"name": "Task 2", // NSString
"repeat": 1, // int
"sub_tasks": [ // NSArray
{ // Is this necessary ?
"sub_task": { // sub task object
"name":"Do This", // NSString
"repeat":2 // int
},
"sub_task": {
"name":"Do That",
"repeat":2
}
} // Is this necessary ?
]
}
} // Is this necessary ?
], // tasks NSArray
"another_string":"some text" // NSString
}
Quick JSON question - Not sure the structure of the arrays is correct (specifically the opening "{" just after the start of the array "["). Is it needed ?
My first attempt to create JSON is to use [NSDictionary dictionaryWithObjectsAndKeys:...] to build up dictionary, and then use [NSJSONSerialization dataWithJSONObject:] with dictionary as parameter to create JSON. However, I'm stuck on the dictionary creation part. I've started with the following:
NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:
#"The Title", #"title",
[NSNumber numberWithInt:revision], #"revision",
// How to create the tasks array ???
but am not sure how to add the NSArray and sub-NSArray, while only adding specific members of the array objects (ie. I don't want all the member fields - eg. For the task object, I want name, repeat and sub-tasks array, but not the date field, and I need to convert repeat field to NSNumber object).
How can I do this in Objective-C ?
By using object literals, you can create a JSON object dictionary like this:
NSDictionary *jsonObject = #{
#"title": #"My Title",
#"revision": #(1),
#"tasks": #[
#{
#"task": #{
#"name": #"Task 2",
#"repeat": #(1),
#"sub_tasks": #[
#{
#"sub_task": {
#"name": #"Do That",
#"repeat": #(2)
}
}
]
}
}
],
#"another_string": #"some text"
};
By adding the # in front of numbers, brackets, and braces, it will create NSNumber, NSDictionary, and NSArray objects.
What you've shared is invalid JSON because it contains duplicate keys within the same object, contains comments, and there's invalid syntax at "title:" where the colon is inside the key.
Here is the correct JSON for what you're trying to represent:
{
"title": "My Title",
"revision": 1,
"tasks": [
{
"name": "Task 1",
"repeat": 1,
"sub_tasks": [
{
"name": "Do This",
"repeat": 2
},
{
"name": "Do That",
"repeat": 2
}
]
},
{
"name": "Task 2",
"repeat": 1,
"sub_tasks": [
{
"name": "Do This",
"repeat": 2
},
{
"name": "Do That",
"repeat": 2
}
]
}
],
"another_string": "some text"
}
I used quicktype to generate the following interface and implementation code. Here's DMTasks.h:
// To parse this JSON:
//
// NSError *error;
// DMTasks *tasks = [DMTasks fromJSON:json encoding:NSUTF8Encoding error:&error]
#import <Foundation/Foundation.h>
#class DMTasks;
#class DMTask;
#class DMSubTask;
NS_ASSUME_NONNULL_BEGIN
#pragma mark - Object interfaces
#interface DMTasks : NSObject
#property (nonatomic, copy) NSString *title;
#property (nonatomic, assign) NSInteger revision;
#property (nonatomic, copy) NSArray<DMTask *> *tasks;
#property (nonatomic, copy) NSString *anotherString;
+ (_Nullable instancetype)fromJSON:(NSString *)json encoding:(NSStringEncoding)encoding error:(NSError *_Nullable *)error;
+ (_Nullable instancetype)fromData:(NSData *)data error:(NSError *_Nullable *)error;
- (NSString *_Nullable)toJSON:(NSStringEncoding)encoding error:(NSError *_Nullable *)error;
- (NSData *_Nullable)toData:(NSError *_Nullable *)error;
#end
#interface DMTask : NSObject
#property (nonatomic, copy) NSString *name;
#property (nonatomic, assign) NSInteger repeat;
#property (nonatomic, copy) NSArray<DMSubTask *> *subTasks;
#end
#interface DMSubTask : NSObject
#property (nonatomic, copy) NSString *name;
#property (nonatomic, assign) NSInteger repeat;
#end
NS_ASSUME_NONNULL_END
And the implementation DMTasks.m:
#import "DMTasks.h"
#define λ(decl, expr) (^(decl) { return (expr); })
static id NSNullify(id _Nullable x) {
return (x == nil || x == NSNull.null) ? NSNull.null : x;
}
NS_ASSUME_NONNULL_BEGIN
#interface DMTasks (JSONConversion)
+ (instancetype)fromJSONDictionary:(NSDictionary *)dict;
- (NSDictionary *)JSONDictionary;
#end
#interface DMTask (JSONConversion)
+ (instancetype)fromJSONDictionary:(NSDictionary *)dict;
- (NSDictionary *)JSONDictionary;
#end
#interface DMSubTask (JSONConversion)
+ (instancetype)fromJSONDictionary:(NSDictionary *)dict;
- (NSDictionary *)JSONDictionary;
#end
static id map(id collection, id (^f)(id value)) {
id result = nil;
if ([collection isKindOfClass:NSArray.class]) {
result = [NSMutableArray arrayWithCapacity:[collection count]];
for (id x in collection) [result addObject:f(x)];
} else if ([collection isKindOfClass:NSDictionary.class]) {
result = [NSMutableDictionary dictionaryWithCapacity:[collection count]];
for (id key in collection) [result setObject:f([collection objectForKey:key]) forKey:key];
}
return result;
}
#pragma mark - JSON serialization
DMTasks *_Nullable DMTasksFromData(NSData *data, NSError **error)
{
#try {
id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:error];
return *error ? nil : [DMTasks fromJSONDictionary:json];
} #catch (NSException *exception) {
*error = [NSError errorWithDomain:#"JSONSerialization" code:-1 userInfo:#{ #"exception": exception }];
return nil;
}
}
DMTasks *_Nullable DMTasksFromJSON(NSString *json, NSStringEncoding encoding, NSError **error)
{
return DMTasksFromData([json dataUsingEncoding:encoding], error);
}
NSData *_Nullable DMTasksToData(DMTasks *tasks, NSError **error)
{
#try {
id json = [tasks JSONDictionary];
NSData *data = [NSJSONSerialization dataWithJSONObject:json options:kNilOptions error:error];
return *error ? nil : data;
} #catch (NSException *exception) {
*error = [NSError errorWithDomain:#"JSONSerialization" code:-1 userInfo:#{ #"exception": exception }];
return nil;
}
}
NSString *_Nullable DMTasksToJSON(DMTasks *tasks, NSStringEncoding encoding, NSError **error)
{
NSData *data = DMTasksToData(tasks, error);
return data ? [[NSString alloc] initWithData:data encoding:encoding] : nil;
}
#implementation DMTasks
+ (NSDictionary<NSString *, NSString *> *)properties
{
static NSDictionary<NSString *, NSString *> *properties;
return properties = properties ? properties : #{
#"title": #"title",
#"revision": #"revision",
#"tasks": #"tasks",
#"another_string": #"anotherString",
};
}
+ (_Nullable instancetype)fromData:(NSData *)data error:(NSError *_Nullable *)error
{
return DMTasksFromData(data, error);
}
+ (_Nullable instancetype)fromJSON:(NSString *)json encoding:(NSStringEncoding)encoding error:(NSError *_Nullable *)error
{
return DMTasksFromJSON(json, encoding, error);
}
+ (instancetype)fromJSONDictionary:(NSDictionary *)dict
{
return dict ? [[DMTasks alloc] initWithJSONDictionary:dict] : nil;
}
- (instancetype)initWithJSONDictionary:(NSDictionary *)dict
{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
_tasks = map(_tasks, λ(id x, [DMTask fromJSONDictionary:x]));
}
return self;
}
- (void)setValue:(nullable id)value forKey:(NSString *)key
{
[super setValue:value forKey:DMTasks.properties[key]];
}
- (NSDictionary *)JSONDictionary
{
id dict = [[self dictionaryWithValuesForKeys:DMTasks.properties.allValues] mutableCopy];
for (id jsonName in DMTasks.properties) {
id propertyName = DMTasks.properties[jsonName];
if (![jsonName isEqualToString:propertyName]) {
dict[jsonName] = dict[propertyName];
[dict removeObjectForKey:propertyName];
}
}
[dict addEntriesFromDictionary:#{
#"tasks": map(_tasks, λ(id x, [x JSONDictionary])),
}];
return dict;
}
- (NSData *_Nullable)toData:(NSError *_Nullable *)error
{
return DMTasksToData(self, error);
}
- (NSString *_Nullable)toJSON:(NSStringEncoding)encoding error:(NSError *_Nullable *)error
{
return DMTasksToJSON(self, encoding, error);
}
#end
#implementation DMTask
+ (NSDictionary<NSString *, NSString *> *)properties
{
static NSDictionary<NSString *, NSString *> *properties;
return properties = properties ? properties : #{
#"name": #"name",
#"repeat": #"repeat",
#"sub_tasks": #"subTasks",
};
}
+ (instancetype)fromJSONDictionary:(NSDictionary *)dict
{
return dict ? [[DMTask alloc] initWithJSONDictionary:dict] : nil;
}
- (instancetype)initWithJSONDictionary:(NSDictionary *)dict
{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
_subTasks = map(_subTasks, λ(id x, [DMSubTask fromJSONDictionary:x]));
}
return self;
}
- (void)setValue:(nullable id)value forKey:(NSString *)key
{
[super setValue:value forKey:DMTask.properties[key]];
}
- (NSDictionary *)JSONDictionary
{
id dict = [[self dictionaryWithValuesForKeys:DMTask.properties.allValues] mutableCopy];
for (id jsonName in DMTask.properties) {
id propertyName = DMTask.properties[jsonName];
if (![jsonName isEqualToString:propertyName]) {
dict[jsonName] = dict[propertyName];
[dict removeObjectForKey:propertyName];
}
}
[dict addEntriesFromDictionary:#{
#"sub_tasks": map(_subTasks, λ(id x, [x JSONDictionary])),
}];
return dict;
}
#end
#implementation DMSubTask
+ (NSDictionary<NSString *, NSString *> *)properties
{
static NSDictionary<NSString *, NSString *> *properties;
return properties = properties ? properties : #{
#"name": #"name",
#"repeat": #"repeat",
};
}
+ (instancetype)fromJSONDictionary:(NSDictionary *)dict
{
return dict ? [[DMSubTask alloc] initWithJSONDictionary:dict] : nil;
}
- (instancetype)initWithJSONDictionary:(NSDictionary *)dict
{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
- (NSDictionary *)JSONDictionary
{
return [self dictionaryWithValuesForKeys:DMSubTask.properties.allValues];
}
#end
NS_ASSUME_NONNULL_END
Now you can create an instance of DMTasks *myTasks, set whatever values or subtasks you'd like, then use [myTasks toJSON:NSUTF8Encoding error:&error] to convert to JSON.

call for nested json objects, in 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);
}

iOS Can't get Dictionary values to an array

I have dictionary:
{
6 = (
{
id = 6;
name = Andrea;
},
{
id = 6;
name = Paolo;
}
);
8 = (
{
id = 8;
name = Maria;
}
);
67 = (
{
id = 67;
name = Francesco;
},
{
id = 67;
name = Sara;
}
);
}
I tried to get Values to array.
My code is:
NSArray *arrayNew= [result valueForKey:#"67"];
NSLog(#"Hello:%#",arrayNew);
But Always i got null value.
My complete code:
NSMutableArray *idArray=[[NSMutableArray alloc]init];
NSString* path = [[NSBundle mainBundle] pathForResource:#"File"
ofType:#"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSMutableData *results11 = [content JSONValue];
NSLog(#"Check:%#",results11);
NSArray *array= [results11 valueForKeyPath:#"field"];
NSMutableDictionary* result = [NSMutableDictionary dictionary];
for (NSDictionary* dict in array)
{
NSNumber* anID = [dict objectForKey:#"id"];
if (![idArray containsObject:[dict objectForKey:#"id"]]) {
// do something
[idArray addObject:[dict objectForKey:#"id"]];
}
NSMutableArray* resultsForID = [result objectForKey:anID];
if (!resultsForID)
{
resultsForID = [NSMutableArray array];
[result setObject:resultsForID forKey:anID];
}
[resultsForID addObject:dict];
}
NSLog(#"Result:%#",result);
NSLog(#"ID arr:%#",idArray);
// NSArray *temp= [results11 valueForKeyPath:#"Response.alertHistory"];
NSString *arrayNew= [result valueForKeyPath:#"67"];
NSLog(#"Hello:%#",arrayNew);
File.txt : {
"field": [
{
"id": 6,
"name": "Andrea"
},
{
"id": 67,
"name": "Francesco"
},
{
"id": 8,
"name": "Maria"
},
{
"id": 6,
"name": "Paolo"
},
{
"id": 67,
"name": "Sara"
}
]
}
Finally with reference of Tommy's solution I solved my issue.
NSArray *commentArray = result[#67];
And my final code:
NSMutableArray *idArray=[[NSMutableArray alloc]init];
NSString* path = [[NSBundle mainBundle] pathForResource:#"File"
ofType:#"txt"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
NSMutableData *results11 = [content JSONValue];
NSLog(#"Check:%#",results11);
NSArray *array= [results11 valueForKeyPath:#"field"];
NSMutableDictionary* result = [NSMutableDictionary dictionary];
for (NSDictionary* dict in array)
{
NSNumber* anID = [dict objectForKey:#"id"];
if (![idArray containsObject:[dict objectForKey:#"id"]]) {
// do something
[idArray addObject:[dict objectForKey:#"id"]];
}
NSMutableArray* resultsForID = [result objectForKey:anID];
if (!resultsForID)
{
resultsForID = [NSMutableArray array];
[result setObject:resultsForID forKey:anID];
}
[resultsForID addObject:dict];
}
NSLog(#"Result:%#",result);
NSMutableArray *arrayNew = [[NSMutableArray alloc] init];
for (int i=0; i<[idArray count]; i++) {
NSArray *commentArray = result[idArray[i]];
NSLog(#"COMM:%#",commentArray);
NSMutableArray *arr=[[NSMutableArray alloc]init];
for (NSDictionary* dict in commentArray)
{
[arr addObject:[dict objectForKey:#"name"]];
}
[arrayNew addObject:arr];
}
NSLog(#"ID arr:%#",idArray);
NSLog(#"Name arr:%#",arrayNew);
File.txt :
{
"field": [
{
"id": 6,
"name": "Andrea"
},
{
"id": 67,
"name": "Francesco"
},
{
"id": 8,
"name": "Maria"
},
{
"id": 6,
"name": "Paolo"
},
{
"id": 67,
"name": "Sara"
}
]
}
My final result:
ID arr:(
6,
67,
8
)
Name arr:(
(
Andrea,
Paolo
),
(
Francesco,
Sara
),
(
Maria
)
)
The most likely reason for this is that your NSDictionary uses integers, not NSStrings, as its keys. In this case this should work:
NSArray *arrayNew= [result objectForKey:#67]; // No quotes
NSMutableArray *arrayNew = [[NSMutableArray alloc] init];
NSArray *commentArray = [dictionary valueForKey:#"67"];
for (NSDictionary *commentDic in commentArray) {
Model *modelObj = [[Model alloc] init];
modelObj = [Model modelFromDictionary:commentDic];
[arrayNew addObject:modelObj]
}
Also you will have to create Model .h and .m class to do the mapping.
and modelFromDictionary method will do the mapping.
.m
#implementation Version
- (NSDictionary *)jsonMapping {
return [[NSDictionary alloc] initWithObjectsAndKeys:
#"id",#"id",
#"name",#"name",
nil];
}
+ (Model *)modelFromDictionary:(NSDictionary *)dictionary {
Model *model = [[Model alloc] init];
NSDictionary *mapping = [model jsonMapping];
for(NSString *attribute in [mapping allKeys]) {
NSString *classProperty = [mapping objectForKey:attribute];
NSString *attributeValue = [dictionary objectForKey:attribute];
if(attributeValue != nil && ![attributeValue isKindOfClass:[NSNull class]]) {
[model setValue:attributeValue
forKey:classProperty];
}
}
return model;
}
.h
#property (nonatomic, strong) NSString *id;
#property (nonatomic, strong) NSString *name;
+ (Model *)modelFromDictionary:(NSDictionary *)dictionary;

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