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"]];
}
}
Related
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
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);
}
I have a problem to communicate with a server. The webserver expects all parameters in the JSON object to be a string. So every number and every boolean in every container needs to be a string.
For my example I have a NSDictionary full of key values (values are all kinds of types - numbers, arrays etc.). For example:
{
"AnExampleNumber":7e062fa,
"AnExampleBoolean":0,
"AnExampleArrayOfNumber":[17,4,8]
}
Has to become:
{
"AnExampleNumber":"7e062fa",
"AnExampleBoolean":"0",
"AnExampleArrayOfNumber":["17","4","8"]
}
I tried the standard NSJSONSerializer but it doesn't give me any option to do what I need. I then tried to transform everything in the dictionary manually to be a string but that seems to be overhead. Does anyone have hint for me? Maybe a serializer that does just that or a function to convert any objects in a container to strings?
This is one way you could do it. It's non-optimized and has no error handling. It only supports the kinds of objects that NSJSONSerializer supports.
#import <Foundation/Foundation.h>
#interface NSObject(SPWKStringify)
- (id)spwk_stringify;
#end
#implementation NSObject(SPWKStringify)
- (id)spwk_stringify
{
if ([self isKindOfClass:[NSDictionary class]]) {
NSDictionary *dict = (NSDictionary *)self;
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
for (NSString *key in [dict allKeys]) {
newDict[key] = [dict[key] spwk_stringify];
}
return newDict;
} else if ([self isKindOfClass:[NSArray class]]) {
NSMutableArray *newArray = [[NSMutableArray alloc] init];
for (id value in ((NSArray *)self)) {
[newArray addObject:[value spwk_stringify]];
}
return newArray;
} else if (self == [NSNull null]) {
return #"null"; // representing null as a string doesn't make much sense
} else if ([self isKindOfClass:[NSString class]]) {
return self;
} else if ([self isKindOfClass:[NSNumber class]]) {
return [((NSNumber *)self) stringValue];
}
return nil;
}
#end
int main(int argc, char *argv[]) {
#autoreleasepool {
NSDictionary *dict = #{
#"AnExampleNumber": #1234567,
#"AnExampleBoolean": #NO,
#"AnExampleNull": [NSNull null],
#"AnExampleArrayOfNumber": #[#17, #4, #8],
#"AnExampleDictionary": #{#"innerKey": #[#55, #{#"anotherDict": #[#"foo", #[#1, #2, #"three"]]}]}
};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[dict spwk_stringify] options:NSJSONWritingPrettyPrinted error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"result: %#", jsonString);
}
}
The output will be:
result: {
"AnExampleNumber" : "1234567",
"AnExampleNull" : "null",
"AnExampleDictionary" : {
"innerKey" : [
"55",
{
"anotherDict" : [
"foo",
[
"1",
"2",
"three"
]
]
}
]
},
"AnExampleBoolean" : "0",
"AnExampleArrayOfNumber" : [
"17",
"4",
"8"
]
}
Note: Please keep in mind that turning [NSNull null] into a string doesn't make any sense and might actually be misleading and dangerous.
Enjoy.
(I assume you mean NSJSONSerializer, not NSSerializer.)
I doubt you'll find a pre-rolled solution to this. It's not a general problem. As you note, this is incorrect JSON, so JSON serializers shouldn't do it.
The best solution IMO is just write the code to transform your NSDictionary into another NSDictionary that is in the form you want. If you really want to make it a generic solution, I suspect that a custom NSDictionary walker with isKindOfClass: is your best bet. Something like this should work:
NSDictionary *myStringDictForDict(NSDictionary *dict); // forward decl if needed
NSArray *myStringArrayForArray(NSArray *array) {
NSMutableArray *result = [NSMutableArray new];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isKindOfClass:[NSArray class]]) {
[result addObject:myStringArrayForArray(obj)];
} else if ([obj isKindOfClass:[NSDictionary class]]) {
[result addObject:myStringDictForDict(obj)];
} else {
[result addObject:[obj description]];
}
}];
return result;
}
NSDictionary *myStringDictForDict(NSDictionary *dict) {
NSMutableDictionary *result = [NSMutableDictionary new];
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([obj isKindOfClass:[NSArray class]]) {
result[key] = myStringArrayForArray(obj);
} else if ([obj isKindOfClass:[NSDictionary class]]) {
result[key] = myStringDictForDict(obj);
} else {
result[key] = [obj description];
}
}];
return result;
}
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.
How can I loop through this part of the json [{first set of values},{data->children->data->body} in objective c?
Json is
[
{
"kind": "Listing"
},
{
"kind": "Listing",
"data": {
"children": [
{
"data": {
"body": "body1"
}
},
{
"data": {
"body": "body2"
}
}
]
}
}
]
My current code is
m_ArrList=[[NSMutableArray alloc]init];
NSDictionary *infomation = [self dictionaryWithContentsOfJSONString:#"surveyquestion.json"];
NSArray *array=[infomation objectForKey:#"data"];
int ndx;
NSLog(#"%#",array);
for (ndx = 0; ndx < [array count]; ndx++) {
NSDictionary *stream = (NSDictionary *)[array objectAtIndex:ndx];
NSArray *string=[stream valueForKey:#"children"];
//i am stuck here
}
What do I do at the "//i am stuck here" ?
You might need to add the values of #"children" dictionary in an array and then parse that array to get the data inside children
[childrenArray addObject:[stream objectForKey:#"children"]];
// finally parse childrenArray
// You Just need to Implement following Lines and you will get all the data for Key Body in children array
NSDictionary *infomation = [self dictionaryWithContentsOfJSONString:#"surveyquestion.json"];
NSArray *string= [[infomation objectForKey:#"data"] objectForKey:#"children"];
[string enumerateObjectsUsingBlock:^(id obj, NSUInteger ind, BOOL *stop){
NSLog(#"Body : %#",[[obj objectForKey:#"data"] objectForKey:#"body"]);
}];
Using NSJSONSerialization try to implement this. Here you need to pass NSString as jsonStr which you need to read from your file.
NSError *jsonError = nil;
id allValues = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:&jsonError];
if(jsonError!=nil)
NSLog(#"Json_Err: %#",jsonError);
NSArray *array=allValues;
for (int ndx = 0; ndx < [array count]; ndx++) {
NSDictionary *stream = (NSDictionary *)[array objectAtIndex:ndx];
NSLog(#"%#",[stream objectForKey:#"kind"]);
NSArray *child = [[stream objectForKey:#"data"] objectForKey:#"children"];
//i am stuck here
for(int i =0; i <[child count];i++)
{
NSDictionary *childData = (NSDictionary *)[child objectAtIndex:i];
//NSLog(#"%#",[childData objectForKey:#"data"]);
NSLog(#"%#",[[childData objectForKey:#"data"] objectForKey:#"body"]);
}
}