iOS收藏codeER.tec

【code_小马】iOS中NSArray对象转jsonStrin

2018-08-14  本文已影响2人  曾经像素有点低
我们是工程师 ——加油 !
//数组转为json字符串
- (NSString *)arrayToJSONString:(NSArray *)array {
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    //    NSString *jsonResult = [jsonTemp stringByReplacingOccurrencesOfString:@" " withString:@""];
    return jsonTemp;
}
    NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"CityData" ofType:@"plist"]];
    NSString * jsonStr = [self arrayToJSONString:array];
    NSLog(@"===%@",jsonStr);

//主要是这两句转换
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] 
//之所以我加上一句
NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//是为了去掉换行符

奋斗吧~!工程师们!


上一篇下一篇

猜你喜欢

热点阅读