1

Is there any good tutorial/source code to parse jSon data into the cocos2d project? I know how to parse jSon (also the XML) into the xcode and display into the tableview but I need to do that for my cocos2d project. Here is what I was trying to do:

#import "Eighties.h"
#import "HelloWorldLayer.h"
#import "GameScene.h"
#import "JSON.h"
#define kLatestKivaLoansURL @"http://api.kivaws.org/v1/loans/search.json?status=fundraising"
@implementation Eighties
@synthesize responseData;
+(CCScene *) scene
{
  // 'scene' is an autorelease object.
  CCScene *scene = [CCScene node];

  // 'layer' is an autorelease object.
  Eighties *layer = [Eighties node];

  // add layer as a child to scene
  [scene addChild: layer];

  // return the scene
  return scene;
}


-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super's" return value
if( (self=[super init]) ) {

    CGSize winSize = [[CCDirector sharedDirector] winSize];

    CCSprite *bg = [CCSprite spriteWithFile:@"bg.jpg"];
    [bg setPosition:ccp(winSize.width/2, winSize.height/2)];
    [self addChild:bg z:0];

    /*
    CCMenuItem *menuItems = [CCMenuItemImage itemWithNormalImage:@"back_pink.png" selectedImage:@"back_blue.png" block:^(id sender) {
        NSLog(@"Pressed");
        [[SimpleAudioEngine sharedEngine] playEffect:@"tongue-clap.wav"];
        [[CCDirector sharedDirector] replaceScene:[CCTransitionFade transitionWithDuration:1.0 scene:[GameScene scene] withColor:ccWHITE]];
    }];
     */


    CCMenuItem *menuItems2 = [CCMenuItemImage itemWithNormalImage:@"back_pink.png" selectedImage:@"back_blue.png" target:self selector:@selector(loadData)];

    menuItems2.position = ccp(winSize.width/2-50, winSize.height/2-50);

    CCMenu *menu = [CCMenu menuWithItems:menuItems2, nil];
    menu.position = ccp(winSize.width/2, winSize.height/2);
    [self addChild:menu];





}
return self;
}

-(void)test {
NSLog(@"Success");
UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Success"
                                                  message:@"Test Method Called"
                                                 delegate:nil
                                        cancelButtonTitle:@"OK"
                                        otherButtonTitles:nil];
[message show];
}

-(void)loadData
{
self.responseData = [NSMutableData data];

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:kLatestKivaLoansURL]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
self.responseData = nil;
}

#pragma mark -
#pragma mark Process loan data
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];

NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;

NSArray* latestLoans = [(NSDictionary*)[responseString JSONValue] objectForKey:@"loans"];
[responseString release];

//choose a random loan
for (int i=0; i<=18; i++) {
    NSDictionary* loan = [latestLoans objectAtIndex:i];

    //fetch the data
    NSNumber* fundedAmount = [loan objectForKey:@"funded_amount"];
    NSNumber* loanAmount = [loan objectForKey:@"loan_amount"];
    //float outstandingAmount = [loanAmount floatValue] - [fundedAmount floatValue];

    //NSString* name = [loan objectForKey:@"name"];
    //NSString* country = [(NSDictionary*)[loan objectForKey:@"location"] objectForKey:@"country"];

    //set the text to the label
    /*
    label.text = [NSString stringWithFormat:@"Latest loan: %@ from %@ needs another $%.2f, please help",
                  name,country,outstandingAmount
                  ];
     */

    NSLog(@"%d",i);
    //NSLog(@"%@",label.text);
    NSLog(@"\n");
    /*
    UIAlertView *message = [[UIAlertView alloc] initWithTitle:name
                                                      message:country
                                                     delegate:nil
                                            cancelButtonTitle:@"OK"
                                            otherButtonTitles:nil];
    [message show];
     */
}

}



@end
KRISH
  • 13
  • 3
jeewan
  • 1,597
  • 5
  • 23
  • 40

2 Answers2

1

There are a lot of ways to deserialize JSON objects, some ways are even baked into the SDK.

This question details a few ways you can approach the problem.

Community
  • 1
  • 1
bibo bode
  • 1,150
  • 1
  • 10
  • 17
  • sorry I could not format the code I posted here... it might be difficult to read. My question is, how can I parse and display jSon data from remote URL into the "Cocos2d" project. I have a class which is sub class of "CCLayer" in cocos2d and not a sub class of UIViewController. I know the parsing of jSon for UIViewController's sub classes but I could not do that for CCLayer's sub classes. Do you know any tutorial about this? – jeewan Dec 19 '12 at 02:54
  • Why are you unable to do the same for CCLayer's sub classes? More information will help :) – bibo bode Dec 19 '12 at 03:09
  • I fixed the issues. The problems was: I was using the JSON parser that has some bugs in it. I tried with the latest version from here: https://github.com/stig/json-framework/downloads and it worked fine. The code I posted worked just with including the latest JSON .h files. – jeewan Dec 19 '12 at 04:05
  • I'm glad it worked out for you, Jeewan, and apologize I was no help :( – bibo bode Dec 19 '12 at 04:05
0

or you can take your JSON and have this utility generate the parsing code for you https://itunes.apple.com/us/app/json-accelerator/id511324989?mt=12

Alex Nolasco
  • 18,750
  • 9
  • 86
  • 81