2018-05-30 项目:JSON解析

一.项目要求

二.代码实现

这次项目中,我把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

  • NSJSONReadingMutableContainers = 转换出来的对象是可变数组或者可变字典
  • NSJSONReadingMutableLeaves = 转换呼出来的OC对象中的字符串是可变的\注意:iOS7之后无效 bug
  • NSJSONReadingAllowFragments = 如果服务器返回的JSON数据,不是标准的JSON,那么就必须使用这个值,否则无法解析
- (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,以后要注意不能照搬,要多思考!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,433评论 30 472
  • 上面一篇文章没有分析完yymodel 。 接着上篇接着分析 static void ModelSetValueFo...
    充满活力的早晨阅读 4,976评论 0 0
  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 30,030评论 8 265
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,904评论 1 32
  • 大幅度发飞大幅度发飞大幅度发飞大幅度发飞大幅度发飞大幅度发飞大幅度发飞大幅度发飞大幅度发飞大幅度发飞大幅度发飞大幅...
    心去处阅读 1,616评论 0 0

友情链接更多精彩内容