FJModel.h
#import <Foundation/Foundation.h>json
//模型類,專門用來存儲數據的類數組
@interface FJModel : NSObject網絡
//用他的屬性來存存儲數據工具
//存儲json解析的簡介;atom
@property (nonatomic,copy) NSString *intro;url
//標題spa
@property (nonatomic,copy) NSString *title;.net
//來源3d
@property (nonatomic,copy) NSString *source;code
//長標題
@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 <Foundation/Foundation.h>
#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數據最外層要麼是字典要麼是數組;
//NSJSONSerialization就是最好的json解析工具;
//參數一:需解析的數據;
//參數二:告訴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);
}
}