iOS 將字典 陣列 轉換成 NSdata 或者 NSString
阿新 • • 發佈:2019-02-17
NSObject+JSONCategories.h
#import <Foundation/Foundation.h> @interface NSObject (JSONCategories) /** * 描述:將NSArray或者NSDictionary轉化為NSData * 引數: * 返回值:轉化後的NSData * */ -(NSData*)JSONData; /** * 描述:將NSArray或者NSDictionary轉化為NSString * 引數: * 返回值:轉化後的NSString * */ -(NSString*)JSONString; @end
NSObject+JSONCategories.m
#import "NSObject+JSONCategories.h" @implementation NSObject (JSONCategories) -(NSString*)JSONString; { NSError* error = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error]; if ([jsonData length] > 0 && error == nil){ NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; return [jsonString autorelease]; }else{ return nil; } } -(NSData*)JSONData{ NSError* error = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error]; if ([jsonData length] > 0 && error == nil){ return jsonData; }else{ return nil; } }