iOS入門-34Json解析02

概述

JSON數據,手動解析並展示在列表中

示例

先看圖

在這裏插入圖片描述

工程目錄結構
在這裏插入圖片描述

示例代碼

User.h

#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
//用戶數據模型
@interface User : NSObject{
    //聲明成員變量
    //名稱
    NSString* _name;
    //年齡
    NSString* _age;
    //id
    NSString* _useId;
}

//屬性對象
@property(retain,nonatomic) NSString* name;
@property(retain,nonatomic) NSString* age;
@property(retain,nonatomic) NSString* userID;
@end
NS_ASSUME_NONNULL_END

User.m

#import "User.h"
@implementation User
//同步屬性和成員變量
@synthesize name = _name;
@synthesize age = _age;
@synthesize userID = _useId;
@end

CategoryBean.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface CategoryBean : NSObject
{
    NSString* _title;
    
    NSMutableArray* _arrayUser;
}

@property NSString* title;

@property NSMutableArray* arrayUser;

@end

NS_ASSUME_NONNULL_END

CategoryBean.m

#import "CategoryBean.h"

@implementation CategoryBean

@synthesize title = _title;
@synthesize arrayUser = _arrayUser;

@end

ViewController.h

#import <UIKit/UIKit.h>
#import "CategoryBean.h"

//實現兩個代理
@interface ViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>

{
    //列表view
    UITableView* _tabV;
    //類別對象
    CategoryBean* _categoryBean;
}
@end

ViewController.m

#import "ViewController.h"
#import "User.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //創建列表控件
    _tabV = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _tabV.delegate = self;
    _tabV.dataSource = self;
    
    [self.view addSubview:_tabV];
    
    //解析JSON數據
    [self parseData];
    
    [_tabV reloadData];
}

//數組數量
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//每個數組中元素個數
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _categoryBean.arrayUser.count;
}

//添加一個頭部view
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return _categoryBean.title;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 80;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString* strID = @"ID";
    UITableViewCell* cell = [_tabV dequeueReusableCellWithIdentifier:strID];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:strID];
    }
    
    //獲取對應的用戶
    User* user = [_categoryBean.arrayUser objectAtIndex:indexPath.row];
    //顯示title爲用戶名
    cell.textLabel.text = user.name;
    cell.detailTextLabel.text = user.age;
    
    return cell;
}

//解析JSON數據函數
-(void) parseData{
    //獲取json文件本地路徑
    NSString* path = [[NSBundle mainBundle] pathForResource:@"gong" ofType:@"json"];
    //將本地json文件加載爲二進制文件
    NSData* data = [NSData dataWithContentsOfFile:path];
    //解析爲字典格式
    NSDictionary* dicRoot = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    //下面是手動解析JSON,這個過程和Java,dart中的思想是一樣的,只是各自語言中api不用。
    //OC中的字典就相當於Java中JsonObject。
    //判斷是否爲字典
    if ([dicRoot isKindOfClass:[NSDictionary class]]) {
        //開始解析
        NSArray* categories = [dicRoot objectForKey:@"categories"];
        
        for (int i=0; i<categories.count; i++) {
            NSDictionary* dicCategory = [categories objectAtIndex:i];
            _categoryBean = [CategoryBean new];
            
            NSString* title = [dicCategory objectForKey:@"title"];
            [_categoryBean setTitle:title];
            
            NSArray* details = [dicCategory objectForKey:@"detail"];
            NSMutableArray* arrayUsers = [NSMutableArray new];
            for (int j=0; j<details.count; j++) {
                NSDictionary* dicUser = [details objectAtIndex:j];
                User* user = [User new];
                user.userID = [dicUser objectForKey:@"id"];
                user.name = [dicUser objectForKey:@"name"];
                user.age = [dicUser objectForKey:@"age"];
                
                [arrayUsers addObject:user];
            }
            
            _categoryBean.arrayUser = arrayUsers;
        }
    }
}
@end

Json數據

{
    "categories": [
        {
            "id": "",
            "detail": [
                {
                    "id": "27230907",
                    "name": "張三",
                    "age": "30",
                },
                {
                    "id": "27230907",
                    "name": "李四",
                    "age": "32",
                },
                {
                    "id": "27230907",
                    "name": "趙五",
                    "age": "40",
                },
                {
                    "id": "27230907",
                    "name": "王六",
                    "age": "30",
                },{
                    "id": "27230907",
                    "name": "李世明",
                    "age": "39",
                },
                {
                    "id": "27230907",
                    "name": "孔子",
                    "age": "77",
                },
                {
                    "id": "27230907",
                    "name": "老子",
                    "age": "90",
                },
                {
                    "id": "27230907",
                    "name": "李志",
                    "age": "50",
                },
            ],
            "title": "用戶列表",
            "imgs": "",
        }
    ],
    "totalcount": "10000",
    "page": "1",
    "status": 200,
    "message": "success"
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章