Demo集合从零开始——我的OC学习之路

2018-05-30 项目:JSON解析

2018-05-30  本文已影响12人  肠粉白粥_Hoben

一.项目要求

二.代码实现

这次项目中,我把JSON数据写入了一个txt文档中,读入后转换成NSString,再转换成NSData,最后把NSData转换成NSDictionary,完成该次项目。首先需要把这次项目的方法都封装成一个类:

#import <Foundation/Foundation.h>

@interface ParseJsonMethod : NSObject

@property (nonatomic, assign) NSDictionary *jsonDictionary;
@property (nonatomic, copy) NSMutableString *jsonString;
//读入文件
- (void) initWithJsonFile: (char *) path;
//解析JSON
- (void) parseWithJsonString;

@end

1.读入文件

-(void) initWithJsonFile:(char *)path
{
    //读入
    FILE *jsonFile = fopen(path, "r");
    char word[200];
    _jsonString = [NSMutableString stringWithCapacity: 50];
    while (fgets(word, 200, jsonFile)) {
        //获取文本内容
        NSString *tmp = [NSString stringWithUTF8String: word];
        [_jsonString appendString: tmp];
    }
}

2.解析JSON

本来想直接用暴力来解析NSString,但是还是上网搜了一下Cocoa库有没有现成的JSON解析方法,结果还真的被我发现了。
首先我们需要将NSString类型的json数据转换成NSData类型,然后获得了NSData后,如果data合法,则使用NSJSONSerialization的方法转换成相应的字典。
其中,option有以下三种参数:(参考https://www.jianshu.com/p/117256de5b95

- (void) parseWithJsonString
{
    //将json数据解码
    NSData* jsonData;
    jsonData = [_jsonString dataUsingEncoding:NSUTF8StringEncoding];
    if (jsonData) {
        _jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData
                                                  options: NSJSONReadingMutableContainers
                                                               error: nil];
    }
}

3.输出结果

使用类别,将NSDictionary里面的中文都转码:

#import "NSDictionary.h"

@implementation NSDictionary(UniCode)

- (NSString*)my_description {
    NSString *desc = [self description];
    desc = [NSString stringWithCString:[desc cStringUsingEncoding:NSUTF8StringEncoding] 
                     encoding:NSNonLossyASCIIStringEncoding];
    return desc;
}

@end

在main.m里面调用我们封装好的方法:

#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "parseJsonMethod.h"
#import "NSDictionary.h"
int main(int argc, char * argv[]) {
    @autoreleasepool {
        char* path = "/Users/huanghongbin/Library/Mobile Documents/com~apple~TextEdit/Documents/jsonFile.txt";
        
        ParseJsonMethod *method = [[ParseJsonMethod alloc] init];
        //获取文本内容
        [method initWithJsonFile: path];
        //解析JSON数据
        [method parseWithJsonString];
        //输出获得的字典。
        //输出时中文转码错误,只能通过类别定义来返回NSString从而输出
        if ([method jsonDictionary])
            NSLog(@"The result dictionary is %@", [[method jsonDictionary] my_description]);
        else
            NSLog(@"JSON数据不合法!");
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

最后成功了!


valid结果.png invalid结果.png

三.踩过的坑

读取文件的时候,不小心照搬了书上的内容,将最后一位替换成了'\0',结果最后一行的括号没有读进去,导致json数据不对,dictionary死活都输出了null,以后要注意不能照搬,要多思考!

上一篇 下一篇

猜你喜欢

热点阅读