▼iPhoneプログラミングメモ▼
JSON


JSONを利用するプログラムを作成する。


ライブラリ準備
JSON Frameworkをダウンロードして解凍し、JSONフォルダをプロジェクトに追加。

ソースコードの記述

JsonEx.h
#import <UIKit/UIKit.h>

//JsonExの宣言
@interface JsonEx : UIView {
    NSMutableArray* _texts;
}
@end

JsonEx.m
#import "JsonEx.h"
#import "JSON.h"

//JsonExの実装
@implementation JsonEx

//初期化
- (id)initWithFrame:(CGRect)frame {
    if (self=[super initWithFrame:frame]) {
        self.backgroundColor=[UIColor whiteColor];

        //通信
        NSURL* url=[NSURL URLWithString:
            @"http://twitter.com/statuses/user_timeline/npaka.json"];
        NSString* jsonStr=[NSString stringWithContentsOfURL:url
            encoding:NSUTF8StringEncoding error:nil];

        //JSONのパース
        _texts=[[NSMutableArray array] retain];
        NSArray* jsonArray=[jsonStr JSONValue];
        for (NSDictionary* dic in jsonArray) {
            NSDictionary* user=[dic objectForKey:@"user"];
            [_texts addObject:[NSString stringWithFormat:@"[%@]%@",
                [user objectForKey:@"name"],
                [dic objectForKey:@"text"]]];
        }
    }
    return self;
}

//メモリ解放
- (void)dealloc {
    [_texts release];
    [super dealloc];
}

//描画
- (void)drawRect:(CGRect)rect {
    //文字列の描画
    [[UIColor blackColor] set];
    UIFont* font=[UIFont systemFontOfSize:16];
    for (int i=0;i<_texts.count;i++) {
        NSString* str=[_texts objectAtIndex:i];
        [str drawAtPoint:CGPointMake(0,20*i) withFont:font];
    }
}
@end



−戻る−