OCのjsonデータ解析
4481 ワード
FJModel.h
#import
//モデルクラス、データを格納するためのクラス
@interface FJModel : NSObject
//彼の属性でデータを保存する
//json解析の概要を格納する;
@property (nonatomic,copy) NSString *intro;
//タイトル
@property (nonatomic,copy) NSString *title;
//出典
@property (nonatomic,copy) NSString *source;
//長い見出し
@property (nonatomic,copy) NSString *long_title;
//ディクショナリによるモデルの初期化(モデル属性への付与)
- (instancetype) initWithDict :(NSDictionary *)dict;
@end
FJMOdel.m
#import "FJModel.h"
@implementation FJModel
- (NSString *)description{
return [NSString stringWithFormat:@"%@ %@ %@ %@",_intro,
_title,_long_title,_source];
}
- (instancetype)initWithDict:(NSDictionary *)dict{
if (self = [super init]) {
//解析した辞書の値を使用して、モデルに対応するメンバー変数に値を割り当てる
_intro = dict[@"intro"];
_title = dict[@"title"];
_long_title = dict[@"long_title"];
_source = dict[@"source"];
}
return self;
}
@end
main.m
#import
#define PATH @"http://yuting.local/shareX/qiushi.json"
#define PATH1 @"http://yuting.local/shareX/sina.json"
#import "FJModel.h"
void test1();
void test2();
int main(int argc, const char * argv[]) {
@autoreleasepool {
test2();
}
return 0;
}
//jsonデータの複数フィールドの値の取得
#pragma mark jsonデータ内の複数のフィールドの値を取得
void test2(){
//1.ネットワークからjsonデータを取得する
NSURL *url = [NSURL URLWithString:PATH1];
NSData *data = [NSData dataWithContentsOfURL:url];
//2.jsonデータを解析し、
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//辞書の下の辞書の配列を取り出す.
NSArray *listArray = dict[@"data"][@"list"];
//モデルを格納するための配列;
NSMutableArray *dataArray = [NSMutableArray array];
//配列を巡って手に入れたすべての辞書.
for (NSDictionary *ndict in listArray) {
//======================
//辞書に格納する必要があるデータを格納するためにモデルを初期化します.
//FJModel *model = [[FJModel alloc]init];
//保存する必要があるフィールドを、対応する属性に配置します.
// model.intro = ndict[@"intro"];
//
// model.title = ndict[@"title"];
//
// model.long_title = ndict[@"long_title"];
//
// model.source = ndict[@"source"];
//=======================
FJModel *model = [[FJModel alloc] initWithDict:ndict];
//モデルのデータを格納する
[dataArray addObject:model];
}
for (FJModel *model in dataArray) {
NSLog(@"%@",model);
}
}
//jsonデータのフィールドの値の取得
#pragma mark jsonデータのフィールドの値を取得
void test1(){
//1.ネットワークからjsonデータを取得する
NSURL * url = [NSURL URLWithString:PATH];
NSData * data = [NSData dataWithContentsOfURL:url];
//NSLog(@"%@",data);
//2.jsonデータを解析する;(前提は、解析するデータのデータがどのようなものかを知ることです.)
//jsonデータの最外層は辞書か配列か.
//NSJSONSerilizationは最高のjson解析ツールです.
//パラメータ1:解析するデータ;
//パラメータ2:json解析ツールがどのようなデータを返す必要があるかを教えます.
//NSJSOnReadingMutableContainers可変コンテナ(配列または辞書)
//NSJSOnReadingMutableLeaves可変文字列
//NSJSOnReadingAllowFragments有効jsonフラグメント
//戻り値:戻り値は具体的にどんなタイプなのか、jsonデータの最外層が何なのかを見てみましょう.
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers error:nil];
//NSLog(@"%@",dict);
//配列を取る
NSArray *items = dict[@"items"];
//配列を巡って、すべての辞書を手に入れる
for (NSDictionary *tdict in items) {
//すべての辞書のcontent内容を手に入れる.
NSString *content = tdict[@"content"];
NSLog(@"%@",content);
}
}