FJModel.h
#import <Foundation/Foundation.h>
//模型类,专门用来存储数据的类
@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 <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);
}
}