iOS 開發之解析Json檔案

weixin_33866037發表於2018-02-09

需求:

本文內容很簡單,但是做一個記錄,如何解析Json檔案。

步驟:

①第一步:先按照Json格式準備一段Json串,如下:

[
    {
        "timeIndex": 24,
        "text": "時辰不清楚"
    }, 
    {
        "timeIndex": 23,
        "text": "子時 23點"
    }, 
    {
        "timeIndex": 0,
        "text": "子時 0點"
    }, 
    {
        "timeIndex": 1,
        "text": "丑時 1點"
    }, 
    {
        "timeIndex": 2,
        "text": "丑時 2點"
    }, 
    {
        "timeIndex": 3,
        "text": "寅時 3點"
    }, 
    {
        "timeIndex": 4,
        "text": "寅時 4點"
    }, 
    {
        "timeIndex": 5,
        "text": "卯時 5點"
    }, 
    {
        "timeIndex": 6,
        "text": "卯時 6點"
    }, 
    {
        "timeIndex": 7,
        "text": "辰時 7點"
    }, 
    {
        "timeIndex": 8,
        "text": "辰時 8點"
    }, 
    {
        "timeIndex": 9,
        "text": "巳時 9點"
    }, 
    {
        "timeIndex": 10,
        "text": "巳時 10點"
    }, 
    {
        "timeIndex": 11,
        "text": "午時 11點"
    }, 
    {
        "timeIndex": 12,
        "text": "午時 12點"
    }, 
    {
        "timeIndex": 13,
        "text": "未時 13點"
    }, 
    {
        "timeIndex": 14,
        "text": "未時 14點"
    }, 
    {
        "timeIndex": 15,
        "text": "申時 15點"
    }, 
    {
        "timeIndex": 16,
        "text": "申時 16點"
    }, 
    {
        "timeIndex": 17,
        "text": "酉時 17點"
    }, 
    {
        "timeIndex": 18,
        "text": "酉時 18點"
    }, 
    {
        "timeIndex": 19,
        "text": "戌時 19點"
    }, 
    {
        "timeIndex": 20,
        "text": "戌時 20點"
    }, 
    {
        "timeIndex": 21,
        "text": "亥時 21點"
    }, 
    {
        "timeIndex": 22,
        "text": "亥時 22點"
    }
]

這個可以在網上搜一些校驗Json格式的平臺進行校驗一下,沒有問題之後就可以放在json.txt或者json.json的檔案中,然後拖入到工程中:


5293487-58a0b49cc9ad2a00.png
Snip20180209_180.png

②第二步:就是解析json檔案了,在需要載入json檔案的地方:

- (void)loadData{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"json.json" ofType:nil];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSError *error;
    NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    if (error) {
        NSLog(@"%@",error);
    }
    NSLog(@"%@",dataArray);
    //自己進行字典轉模型,此處省略
    
    //這裡進行tableView的重新整理操作
    [self.tableView reloadData];
}

好吧,記錄內容就到這裡了,好吧,很簡單,非常簡單,寫不下去了,以上!!!


5293487-69d7acfbf417f111.gif
藍瘦.gif

相關文章