溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2020-10-04 09:01:40 來源:網(wǎng)絡(luò) 閱讀:1487 作者:杜甲同學(xué) 欄目:移動開發(fā)

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


代碼下載地址:     "大字典 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
{
      //用這個類方法進(jìn)行初始化的時候,都會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;
//將多個字典嵌套的數(shù)據(jù)取出的思路是為每一個字典對應(yīng)的建一個數(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
{
    //用這個類方法進(jìn)行初始化的時候,都會alloc一次,因此就會新分配一塊空間
    return [[Status alloc] initWithJsonDictionary:dic];
}




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

我們新建一個試圖控制器用來顯示數(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.
    //添加一個按鈕點(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);
}




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

ViewController.h代碼如下:


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





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

需要在Xib中拖一個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);
                                              
                                              
    //初始化一個數(shù)組
    NSMutableArray* tempArr = [NSMutableArray array];
    //將數(shù)組中的字典放入Status模型中,大家在這里會有一個疑問將數(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" 這個名字的消息對應(yīng)的方法中
    [[NSNotificationCenter defaultCenter] postNotificationName:@"getArray" object:tempArr];
                                              
                                              
                                              
                                              
    //切換視圖控制器
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeVC" object:nil];
}


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI