Json xcode get data - iphone

I have a json http://gdata.youtube.com/feeds/api/users/ruflixnet/playlists?v=2&alt=jsonc
and i want to get id,title and size, but don't now how to do that.

i recommend JSONKit (look at the Benchmarks)
A Very High Performance Objective-C JSON Library
Parsing

Use the SBJSON libraries for example, IVe been using them all time and they are pretty good.
You have a tutorial here:
http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c

download the JSON library and include that in your project than make this following class for your data
Make NSObject class
ObjectData.h
#interface ObjectData : NSObject {
NSString *id;
NSString *title;
NSString *size;
}
#property(nonatomic,retain) NSString *id;
#property(nonatomic,retain) NSString *title;
#property(nonatomic,retain) NSString *size;
#end
ObjectData.M
#import ObjectData.h
#implementation ObjectData
#synthesize id;
#synthesize title;
#synthesize size;
#end
Make another DataController Class
#import <Foundation/Foundation.h>
#interface DataController : NSObject {
}
+ (id)staticVersion;
- (NSMutableArray *) startParsing:(NSString *)theURLString;
end
#import "DataController.h"
#implementation DataController
DataController *theInstance;
+(id)staticVersion
{
if(!theInstance){
theInstance = [[DataController alloc] init];
}
return theInstance;
}
- (NSMutableArray *) startParsing:(NSString *)theURLString {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",theURLString]];
NSString *fileContent= [NSString stringWithContentsOfURL:url];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];
NSArray *items = (NSArray *) data ;
return items;
}
#end
And in View Did load
NSArray *tempArray =[[DataController staticVersion] startParsing:serverName];
for (int i = 0; i<[tempArray count]; i++) {
id *item = [tempArray objectAtIndex:i];
NSDictionary *dict = (NSDictionary *) item;
ObjectData *theObject =[[ObjectData alloc] init];
[theObject setid:[dict objectForKey:#"id"]];
[theObject settitle:[dict objectForKey:#"title"]];
[theObject setsize:[dict objectForKey:#"size"]];
[resultArray addObject:theObject];
[theObject release];
theObject=nil;
At last make preferenc.h file and give the your json data path
#import <Foundation/Foundation.h>
#define serverName #"http://gdata.youtube.com/feeds/api/users/ruflixnet/playlists?v=2&alt=jsonc"
hope this works fine

use SBJson
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableDictionary *dicRes = [parser objectWithString:stringFromServer error:nil];

Related

how to parse json data from a string instead of a URL

I want to parse a json data which is in NSString how can i do this
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",data);
NSArray *tempArray =[[DataController staticVersion] startParsing:data];
for (int i = 0; i<[tempArray count]; i++) {
id *item = [tempArray objectAtIndex:i];
NSDictionary *dict = (NSDictionary *) item;
SearchCode *theObject =[[SearchCode alloc] init];
[theObject setCodeValue:[dict objectForKey:#"CodeValue"]];
[theObject setCodeDescription:[dict objectForKey:#"CodeAddedDate"]];
[theObject setCodeAddedDate:[dict objectForKey:#"CodeAddedDate"]];
[theObject setCodeID:[dict objectForKey:#"CodeID"]];
[theObject setUpdateDateTime:[dict objectForKey:#"UpdateDateTime"]];
[cptArray addObject:theObject];
[theObject release];
theObject=nil;
}
DataController Class
#interface DataController : NSObject {
}
+ (id)staticVersion;
- (NSMutableArray *) startParsing:(NSString *)theURLString;
#end
#import "DataController.h"
#import "JSON.h"
#implementation DataController
DataController *theInstance;
+(id)staticVersion
{
if(!theInstance){
theInstance = [[DataController alloc] init];
}
return theInstance;
}
- (NSMutableArray *) startParsing:(NSString *)theURLString {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",theURLString]];
NSString *fileContent= [NSString stringWithContentsOfURL:url];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];
NSArray *items = (NSArray *) data ;
return items;
}
#end
This Post contains classes to parse JSON, XML etc. I have been using these.
In the new sdk you do not have to use external classes to parse your JSon you can use NSJSONSerialization witch is Available in iOS 5.0 and later.
To parse a json String using this class you will need to convert your NSString to NSData, you can do that with:
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
After that you can use the method to convert the data to json:
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
Your returned type will depend, because it will be like your json, if your json is an array, it will be an array, if is a dictionary, it will be a dictionary, and so on.
From apple documentation:
An object that may be converted to JSON must have the following
properties:
The top level object is an NSArray or NSDictionary. All objects are
instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull. All
dictionary keys are instances of NSString. Numbers are not NaN or
infinity.
Hope it help you.

Leaky Custom Object for storing data from a plist

I have made a very simple custom object pictureData.
Here is the .h file
#import <Foundation/Foundation.h>
#interface pictureData : NSObject {
NSString *fileName;
NSString *photographer;
NSString *title;
NSString *license;
}
#property (nonatomic, retain) NSString *fileName;
#property (nonatomic, retain) NSString *photographer;
#property (nonatomic, retain) NSString *title;
#property (nonatomic, retain) NSString *license;
+(pictureData*)picDataWith:(NSDictionary*)dictionary;
#end
The .m file
#import "pictureData.h"
#implementation pictureData
#synthesize fileName;
#synthesize photographer;
#synthesize title;
#synthesize license;
+ (pictureData*)picDataWith:(NSDictionary *)dictionary {
pictureData *tmp = [[[pictureData alloc] init] autorelease];
tmp.fileName = [dictionary objectForKey:#"fileName"];
tmp.photographer = [dictionary objectForKey:#"photographer"];
tmp.title = [dictionary objectForKey:#"title"];
tmp.license = [dictionary objectForKey:#"license"];
return tmp;
}
-(void)dealloc {
[fileName release];
[photographer release];
[title release];
[license release];
}
#end
I then set up these objects in an array, like so:
NSString *path = [[NSBundle mainBundle] pathForResource:#"pictureLicenses" ofType:#"plist"];
NSArray *tmpDataSource = [NSArray arrayWithContentsOfFile:path];
NSMutableArray *tmp = [[NSMutableArray alloc] init];
self.dataSource = tmp;
[tmp release];
for (NSDictionary *dict in tmpDataSource) {
pictureData *pic = [pictureData picDataWith:dict];
NSLog(#"%#", pic.title);
[self.dataSource addObject:pic];
}
Everything works smashingly. I have a table view which loads the proper picture images, and information, no problem. Upon running Instruments for leaks, I see that my pictureData object is leaks with every allocation.
I would assume that with having my object autoreleased I would not have to worry about manually allocating and deallocating them.
Perhaps is my issue that I use autorelease, which the autoReleasePool keeps a retain count of +1 and then when I add a pictureData object to my array, that also retains it? Thank you all for your time!
edit: Don't forget to call super! Thank you Sam!
Change dealloc to:
-(void)dealloc {
[fileName release];
[photographer release];
[title release];
[license release];
[super dealloc];
}
(call [super dealloc])
In your function, change the return value to include autorelease, like
+ (pictureData*)picDataWith:(NSDictionary *)dictionary
{
...
...
return [tmp autorelease];
}
When you add pictureData object to dataSource, you increase the retain count, so you should autorelease it while returning.
Hope it helps.

NSArray With NSString Is This Even Possible?

I am trying to build a Grouped Sectioned View. I want to set an array as an object in the dictionary but I came across the empty array Issues.
Is this Even possible????? Is There a trick ????
#import "RootViewController.h"
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// Get the specific Node for this row.
Nodes *nodes = (Nodes *)[nodesMArray objectAtIndex:indexPath.row];
// Create the Details View Controller and initialize it.
nodesDetailView *viewController = [[nodesDetailView alloc] initWithStyle:UITableViewStyleGrouped ];
[[self navigationController] pushViewController:viewController animated:YES];
// Set the title of the view to the nodes name
viewController.title = [nodes computer_name];
//Information
//Network Data
viewController.ipaddress= [nodes ipaddress];
viewController.subnet_mask= [nodes subnet_mask];
viewController.gateway= [nodes gateway];
viewController.domain_name= [nodes domain_name];
}
#import "nodesDetailViewController. h
#interface nodesDetailView : UITableViewController{
//Network Data
NSString *ipaddress;
NSString *subnet_mask;
NSString *gateway;
NSString *domain_name;
//Grouped
NSMutableArray *Keys;
NSMutableDictionary *Contents;
}
#property (nonatomic, retain) NSMutableArray *Keys;
#property (nonatomic, retain) NSMutableDictionary *Contents;
#property (nonatomic, retain) NSString *ipaddress;
#property (nonatomic, retain) NSString *subnet_mask;
#property (nonatomic, retain) NSString *gateway;
#property (nonatomic, retain) NSString *domain_name;
#end
#import "nodesDetailViewController. m
#synthesize .......
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
NSMutableArray *keys = [[NSMutableArray alloc] init];
NSMutableDictionary *contents = [[NSMutableDictionary alloc] init];
NSString *network = #"Network Data";
NSString *product = #"Product Details";
//IS THIS POSSIBLE ??????? Because I get An Empty array
[contents setObject:[NSArray arrayWithObjects: ipaddress,subnet_mask, gateway, domain_name, nil] forKey:network];
return self;
}
Thank You In Advance.
All of those strings that you are adding to the array haven't even been allocated/initialized yet. That's why the array is empty. You can't just go: NSString *emptyString; and then go: [myArray addObject:emptyString];. Your strings are all empty.
Check the values u are passing from the table view. They maybe nil. I just used this much of data and i m getting correct NSLog.
NSMutableDictionary *contents = [[NSMutableDictionary alloc] init];
NSString *my = #"kk";
NSString *my1 = #"polko";
[contents setObject:[NSArray arrayWithObjects: my1,my, nil] forKey:#"o"];
NSLog(#"%#" , contents);
For Those Who are wondering: Problem Solved My code was fine. the problem was :
it was in the wrong place.
The Code Supposed to be in - (void)viewDidLoad and not in - (id)initWithStyle:
I want to thank everybody who took the time to look in to it.
I have no idea why i put the code there to begin with.
Thanx Again

Objective-C error while implementing class?

I have this class
#import <Foundation/Foundation.h>
#interface SubscriptionArray : NSObject{
NSString *title;
NSString *source;
NSString *htmlUrl;
}
#property (nonatomic,retain) NSString *title;
#property (nonatomic,retain) NSString *source;
#property (nonatomic,retain) NSString *htmlUrl;
#end
and the implementation file is this one:
#import "SubscriptionArray.h"
#implementation SubscriptionArray
#synthesize title,source,htmlUrl;
-(void)dealloc{
[title release];
[source release];
[htmlUrl release];
}
#end
When I use the class like in this example I get an EXEC_BAD_ACCESS error:
for (NSDictionary *element in subs){
SubscriptionArray *add;
add.title=[element objectForKey:#"title"]; //ERROR Happens at this line
add.source=[element objectForKey:#"htmlUrl"];
add.htmlUrl=[element objectForKey:#"id"];
[subscriptions addObject:add];
}
Can someone help me?
P.S. Subscriptions is a NSMutableArray
You need to allocate your SubscriptionArray object like so: SubscriptionArray *add = [[SubscriptionArray alloc] init];
Your for loop will therefore look something like this:
for (NSDictionary *element in subs){
SubscriptionArray *add = [[SubscriptionArray alloc] init];
add.title=[element objectForKey:#"title"];
add.source=[element objectForKey:#"htmlUrl"];
add.htmlUrl=[element objectForKey:#"id"];
[subscriptions addObject:add];
[add release];
}
You need to initialize your SubscriptionArray. i.e.
SubscriptionArray *add = [SubscriptionArray new];

Variable is not a CFString

I am getting value from JSON it gives exception var is not CFString.
below is the link from which i am getting data
http://www.krsconnect.no/community/api.html?method=categories&appid=620&mainonly=true
NSString *test = aBook.catId;
Book Class
#interface Book : NSObject {
NSString *catId;
NSString *name;
}
#property(nonatomic,retain)NSString*catId;
#property(nonatomic,retain) NSString *name;
#end
#import "Book.h"
#implementation Book
#synthesize catId,name;
-(id)init{
self=[super init];
}
- (id)initWithDictionary:(NSDictionary*) dict {
self.catId = [dict valueForKey:#"categoryId"];
self.name = [dict valueForKey:#"name"];
return self;
}
- (void)dealloc {
[catId release];
[name release];
[super dealloc];
}
#end
Its an integer maybe. Use this.
NSString* test = [NSString stringWithFormat:#"%d",aBook.catId];
I think this question should help you
Replace multiple characters in a string in Objective-C?
CFStringRef aCFString = (CFStringRef)aNSString;
works perfectly and transparently. Likewise:
NSString *aNSString = (NSString *)aCFString;