『技术栈』iOSiOS工具学习程序员

NSString(JSON),NSArray/NSDiction

2015-09-02  本文已影响3639人  点呀点
- (void)viewDidLoad {
    [super viewDidLoad];

    NSMutableDictionary *parameter = [[NSMutableDictionary alloc] init];
    [parameter setObject:@"zhangsan" forKey:@"User"];
    [parameter setObject:@"123" forKey:@"Pwd"];
    
    NSDictionary *parameter1 = @{
                           @"name": @"zhangsan",
                           @"age" : @23,
                           @"book" : @[
                                   @"iOS",
                                   @"Swift"
                                   ]
                           };
    NSArray *array = @[parameter, parameter1];
    
    NSData *jsonData =[array arrayOrNSDictionaryToNSData]; // NSArray/NSDictionary==>NSData
    NSLog(@"jsonData%@",jsonData);
    
    
    // NSData==>NSString
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"jsonString=%@",jsonString); // [{"Pwd":"123","User":"zhangsan"},{"name":"zhangsan","age":18,"book":["iOS","Swift"]}]
    // NSString==>NSData
    jsonData = [jsonString dataUsingEncoding:NSASCIIStringEncoding];
    
    NSDictionary *dict =[jsonString stringToNSArrayOrNSDictionary]; // NSString==>NSArray/NSDictionary
    NSLog(@"dict=%@",dict);
    /*
    [
     {
         "Pwd" : "123",
         "User" : "zhangsan"
     },
     {
         "name" : "zhangsan",
         "age" : 23,
         "book" : [
                   "iOS",
                   "Swift"
                   ]
     }
     ]
    */
}

NSString+JSONCategories.h
#import <Foundation/Foundation.h>

@interface NSString (JSONCategories)
-(id)stringToNSArrayOrNSDictionary;
@end
NSString+JSONCategories.m
#import "NSString+JSONCategories.h"

@implementation NSString (JSONCategories)

// NSString==>NSArray/NSDictionary
-(id)stringToNSArrayOrNSDictionary
{
    NSData* data = [self dataUsingEncoding:NSUTF8StringEncoding];
    __autoreleasing NSError* error = nil;
    id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; // options:NSJSONReadingAllowFragments
    if (error != nil) return nil;
    return result;
}
@end
NSObject+JSONCategories.h
#import <Foundation/Foundation.h>

@interface NSObject (JSONCategories)
- (NSData*)arrayOrNSDictionaryToNSData;
@end
NSObject+JSONCategories.m
#import "NSObject+JSONCategories.h"

@implementation NSObject (JSONCategories)
// NSArray/NSDictionary==>NSData
- (NSData*)arrayOrNSDictionaryToNSData
{
    NSError* error = nil;
    id result = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&error];
    if (error != nil) return nil;
    return result;
}
@end
上一篇下一篇

猜你喜欢

热点阅读