Json數(shù)據(jù)解析后分類思路

Json數(shù)據(jù)解析后分類思路

創(chuàng)新互聯(lián)建站專業(yè)為企業(yè)提供景東網(wǎng)站建設(shè)、景東做網(wǎng)站、景東網(wǎng)站設(shè)計(jì)、景東網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)與制作、景東企業(yè)網(wǎng)站模板建站服務(wù),十載景東做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。

代碼下載地址:     "大字典 2.zip"

http://vdisk.weibo.com/s/HzjOj

我們這里已從新浪微博中請求回來的數(shù)據(jù)作為例子。為了讓工程簡化,我將數(shù)據(jù)寫入到本地了。這里主要是為了學(xué)習(xí)如何將Json數(shù)據(jù)解析分類。

新浪微博請求返回來的數(shù)據(jù)大致格式如下:

{
    "statuses": [
        {
            "created_at": "Tue May 31 17:46:55 +0800 2011",
            "id": 11488058246,
            "text": "求關(guān)注。",
            "source": "<a  rel="nofollow">新浪微博</a>",
            "favorited": false,
            "truncated": false,
            "in_reply_to_status_id": "",
            "in_reply_to_user_id": "",
            "in_reply_to_screen_name": "",
            "geo": null,
            "mid": "5612814510546515491",
            "reposts_count": 8,
            "comments_count": 9,
            "annotations": [],
            "user": {
                "id": 1404376560,
                "screen_name": "zaku",
                "name": "zaku",
                "province": "11",
                "city": "5",
                "location": "北京 朝陽區(qū)",
                "description": "人生五十年,乃如夢如幻;有生斯有死,壯士復(fù)何憾。",
                "url": "http://blog.sina.com.cn/zaku",
                "profile_p_w_picpath_url": "http://tp1.sinaimg.cn/1404376560/50/0/1",
                "domain": "zaku",
                "gender": "m",
                "followers_count": 1204,
                "friends_count": 447,
                "statuses_count": 2908,
                "favourites_count": 0,
                "created_at": "Fri Aug 28 00:00:00 +0800 2009",
                "following": false,
                "allow_all_act_msg": false,
                "remark": "",
                "geo_enabled": true,
                "verified": false,
                "allow_all_comment": true,
                "avatar_large": "http://tp1.sinaimg.cn/1404376560/180/0/1",
                "verified_reason": "",
                "follow_me": false,
                "online_status": 0,
                "bi_followers_count": 215
            }
        },
        ...
    ],
    "previous_cursor": 0,                    // 暫未支持
    "next_cursor": 11488013766,     // 暫未支持
    "total_number": 81655
}

以上的示例來自新浪微博官網(wǎng)。我標(biāo)出的紅色字體 ,是我們JSon解析分類的依據(jù),他們都是字典,也就是說JSon解析分類的思路是按照字典去新建類,類與類之間的嵌套關(guān)系和JSon數(shù)據(jù)的格式相同,這我JSon解析的方法。

我來看一下代碼如何實(shí)現(xiàn)的:

新建User類用來存放user字典中的內(nèi)容。

.h文件如下:

#import <Foundation/Foundation.h>
@interface User : NSObject
@property (strong, nonatomic) NSString* screen_name;
-(User*)initWithJsonDictionary:(NSDictionary*)dic;
+(User*)UserWithJsonDictionary:(NSDictionary*)dic;
@end

.m文件如下:

@implementation User
-(User*)initWithJsonDictionary:(NSDictionary *)dic
{
    if (self = [super init]) {
                                                                                                                                 
        self.screen_name = [dic objectForKey:@"screen_name"];
                                                                                                                                
    }
    return self;
}
+(User*)UserWithJsonDictionary:(NSDictionary *)dic
{
      //用這個(gè)類方法進(jìn)行初始化的時(shí)候,都會alloc一次,因此就會新分配一塊空間
    return [[User alloc] initWithJsonDictionary:dic];
}

新建Status類用來存放statuses字典中的內(nèi)容。


.h文件如下:

#import <Foundation/Foundation.h>
#import "User.h"
@interface Status : NSObject
@property (strong, nonatomic) NSString* userID;
//將多個(gè)字典嵌套的數(shù)據(jù)取出的思路是為每一個(gè)字典對應(yīng)的建一個(gè)數(shù)據(jù)模型的類
//例如:User類
@property (strong , nonatomic) User* user;
-(Status*)initWithJsonDictionary:(NSDictionary*)dic;
+(Status*)statusWithJsonDictionary:(NSDictionary*)dic;
@end

.m文件如下:

@implementation Status
-(Status*)initWithJsonDictionary:(NSDictionary *)dic
{
    if (self = [super init]) {
        self.userID = [dic objectForKey:@"idstr"];
        NSDictionary* userDic = [dic objectForKey:@"user"];
        if (userDic) {
                                                                                                                     
            self.user = [User UserWithJsonDictionary:userDic];
                                                                                                                     
        }
                                                                                                                 
    }
    return self;
}
+(Status*)statusWithJsonDictionary:(NSDictionary *)dic
{
    //用這個(gè)類方法進(jìn)行初始化的時(shí)候,都會alloc一次,因此就會新分配一塊空間
    return [[Status alloc] initWithJsonDictionary:dic];
}


為了模擬在真實(shí)項(xiàng)目中,獲得數(shù)據(jù)的類和顯示數(shù)據(jù)的類不在一個(gè)類中

我們新建一個(gè)試圖控制器用來顯示數(shù)據(jù),我們顯示數(shù)據(jù)的位置是在控制臺。

OtherViewController.h代碼如下:

#import <UIKit/UIKit.h>
@interface OtherViewController : UIViewController
@property (strong , nonatomic) NSArray* statusArr;
@end

OtherViewController.m代碼實(shí)現(xiàn)如下:

//用來接收通過消息機(jī)制發(fā)送來的數(shù)據(jù)
-(void)getArray:(NSNotification*)aNotification
{
    self.statusArr = aNotification.object;
                                                                      
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //添加一個(gè)按鈕點(diǎn)擊顯示數(shù)據(jù)
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(30, 30, 30, 30);
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(displayUserInfo) forControlEvents:UIControlEventTouchUpInside];
}

-(void)displayUserInfo
{
    Status* status = [self.statusArr objectAtIndex:0];
    NSLog(@"status.userID = %@",status.userID);
    NSLog(@"status.user.screen_name = %@",status.user.screen_name);
}

最后,我們來看一下最后的一個(gè)類,我們從這個(gè)類中獲取數(shù)據(jù),獲取數(shù)據(jù)的本地文件在代碼例子中。

ViewController.h代碼如下:

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
-(IBAction)changeVC:(id)sender;
@end

ViewController.m文件的代碼實(shí)現(xiàn)如下:

需要在Xib中拖一個(gè)Button與下面的方法相關(guān)聯(lián)

-(IBAction)changeVC:(id)sender
{
    //將JSON格式的數(shù)據(jù)文件的路徑找出
    NSString* path = [[NSBundle mainBundle] pathForResource:@"jsonTest" ofType:@"json"];
    //將數(shù)據(jù)放入NSData中
    NSData* data = [NSData dataWithContentsOfFile:path];
    //JSON解析
    NSDictionary* dic =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//    NSLog(@"dic = %@",dic);
                                           
    NSArray* arr = [dic objectForKey:@"statuses"];
    NSLog(@"%d",arr.count);
    NSLog(@"arr = %@",arr);
                                              
                                              
    //初始化一個(gè)數(shù)組
    NSMutableArray* tempArr = [NSMutableArray array];
    //將數(shù)組中的字典放入Status模型中,大家在這里會有一個(gè)疑問將數(shù)組中的字典都放入模型中,怎么區(qū)分不同數(shù)組中的數(shù)據(jù)?
    for (NSDictionary* item in arr) {
        //答案在statusWithJsonDictionary:的類方法中見該方法注釋
        Status* status = [Status statusWithJsonDictionary:item];
        NSLog(@"item = %@ ",item);
                                                  
                                                  
                                                  
        //將Status類型的對象放入數(shù)組中
        [tempArr addObject:status];
    }
    //將tempArr數(shù)組通過消息中心發(fā)送到@"getArray" 這個(gè)名字的消息對應(yīng)的方法中
    [[NSNotificationCenter defaultCenter] postNotificationName:@"getArray" object:tempArr];
                                              
                                              
                                              
                                              
    //切換視圖控制器
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeVC" object:nil];
}


當(dāng)前題目:Json數(shù)據(jù)解析后分類思路
本文鏈接:http://muchs.cn/article12/jpjogc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號、網(wǎng)站制作、小程序開發(fā)、云服務(wù)器、自適應(yīng)網(wǎng)站、做網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)