首页 > 代码库 > NSJSONSerialization(category)的一个扩展类

NSJSONSerialization(category)的一个扩展类

.h文件

//
//  NSJSONSerialization+Manage.h
//  SVPullToRefreshDemo
//
//  Created by Fuer on 14-7-4.
//  Copyright (c) 2014年 Home. All rights reserved.
//

#import <Foundation/Foundation.h>
/**
 * The domain for NSErrors generated by the NSJSONSerialization+UAAdditions methods.
 */
extern NSString * const UAJSONSerializationErrorDomain;

NS_ENUM(NSInteger, UAJSONSerializationErrorCode) {
    UAJSONSerializationErrorCodeInvalidObject
};


@interface NSJSONSerialization (Manage)
/**
 * Converts a Foundation object to a JSON formatted NSString
 * @param jsonObject Foundation object to convert
 * @return NSString formatted as JSON, or nil if an error occurs
 * @note Writing JSON strings with this method defaults to no NSJSONWritingOptions, and does not accept fragments.
 */
+ (NSString *)stringWithObject:(id)jsonObject;

/**
 * Converts a Foundation object to a JSON formatted NSString
 * @param jsonObject Foundation object to convert
 * @param error An NSError pointer for storing errors, if applicable.
 * @return NSString formatted as JSON, or nil if an error occurs
 * @note Writing JSON strings with this method defaults to no NSJSONWritingOptions, and does not accept fragments.
 */
+ (NSString *)stringWithObject:(id)jsonObject error:(NSError **)error;

/**
 * Converts a Foundation object to a JSON formatted NSString
 * @param jsonObject Foundation object to convert
 * @param acceptingFragments `YES` if objects representing JSON value fragments are acceptable, `NO` otherwise.
 * @return NSString formatted as JSON, or nil if an error occurs.
 * @note Writing JSON strings with this method defaults to no NSJSONWritingOptions.
 */
+ (NSString *)stringWithObject:(id)jsonObject acceptingFragments:(BOOL)acceptingFragments;

/**
 * Converts a Foundation object to a JSON formatted NSString
 * @param jsonObject Foundation object to convert
 * @param acceptingFragments `YES` if objects representing JSON value fragments are acceptable, `NO` otherwise.
 * @param error An NSError pointer for storing errors, if applicable.
 * @return NSString formatted as JSON, or nil if an error occurs.
 * @note Writing JSON strings with this method defaults to no NSJSONWritingOptions.
 */
+ (NSString *)stringWithObject:(id)jsonObject acceptingFragments:(BOOL)acceptingFragments error:(NSError **)error;

/**
 * Converts a Foundation object to a JSON formatted NSString
 * @param jsonObject Foundation object to convert
 * @param opt NSJSONWritingOptions options
 * @return NSString formatted as JSON, or nil if an error occurs
 */
+ (NSString *)stringWithObject:(id)jsonObject options:(NSJSONWritingOptions)opt;

/**
 * Converts a Foundation object to a JSON formatted NSString
 * @param jsonObject Foundation object to convert
 * @param opt NSJSONWritingOptions options
 * @param error An NSError pointer for storing errors, if applicable.
 * @return NSString formatted as JSON, or nil if an error occurs
 */
+ (NSString *)stringWithObject:(id)jsonObject options:(NSJSONWritingOptions)opt error:(NSError **)error;


/**
 * Create a Foundation object from JSON string
 * @param jsonString the JSON NSString to convert
 * @return A Foundation object, or nil if an error occurs.
 * @note Creating objects with this method defaults to NSJSONReadingMutableContainers options.
 */
+ (id)objectWithString:(NSString *)jsonString;

/**
 * Create a Foundation object from JSON string
 * @param jsonString the JSON NSString to convert
 * @param opt NSJSONReadingOptions
 * @return A Foundation object, or nil if an error occurs.
 */
+ (id)objectWithString:(NSString *)jsonString options:(NSJSONReadingOptions)opt;

/**
 * Create a Foundation object from JSON string
 * @param jsonString the JSON NSString to convert
 * @param opt NSJSONReadingOptions
 * @param error An NSError pointer for storing errors, if applicable.
 * @return A Foundation object, or nil if an error occurs.
 */
+ (id)objectWithString:(NSString *)jsonString options:(NSJSONReadingOptions)opt error:(NSError **)error;


@end

.m文件

//
//  NSJSONSerialization+Manage.m
//  SVPullToRefreshDemo
//
//  Created by Fuer on 14-7-4.
//  Copyright (c) 2014年 Home. All rights reserved.
//
#import "NSJSONSerialization+Manage.h"


@implementation NSJSONSerialization (Manage)

NSString * const UAJSONSerializationErrorDomain = @"com.urbanairship.json_serialization";

+ (NSString *)stringWithObject:(id)jsonObject {
    return [NSJSONSerialization stringWithObject:jsonObject options:0 acceptingFragments:NO error:nil];
}

+ (NSString *)stringWithObject:(id)jsonObject error:(NSError **)error {
    return [NSJSONSerialization stringWithObject:jsonObject options:0 acceptingFragments:NO error:error];
}

+ (NSString *)stringWithObject:(id)jsonObject options:(NSJSONWritingOptions)opt {
    return [NSJSONSerialization stringWithObject:jsonObject options:opt acceptingFragments:NO error:nil];
}

+ (NSString *)stringWithObject:(id)jsonObject options:(NSJSONWritingOptions)opt error:(NSError **)error {
    return [NSJSONSerialization stringWithObject:jsonObject options:opt acceptingFragments:NO error:error];
}

+ (NSString *)stringWithObject:(id)jsonObject acceptingFragments:(BOOL)acceptingFragments {
    return [NSJSONSerialization stringWithObject:jsonObject options:0 acceptingFragments:acceptingFragments error:nil];
}

+ (NSString *)stringWithObject:(id)jsonObject acceptingFragments:(BOOL)acceptingFragments error:(NSError **)error {
    return [NSJSONSerialization stringWithObject:jsonObject options:0 acceptingFragments:acceptingFragments error:error];
}

+ (NSString *)stringWithObject:(id)jsonObject
                       options:(NSJSONWritingOptions)opt
            acceptingFragments:(BOOL)acceptingFragments
                         error:(NSError **)error {
    if (!jsonObject) {
        return nil;
        
    }
    
    if (!acceptingFragments ||
        ([jsonObject isKindOfClass:[NSArray class]] || [jsonObject isKindOfClass:[NSDictionary class]])) {
        if (![NSJSONSerialization isValidJSONObject:jsonObject]) {
            if (error) {
                NSString *msg = [NSString stringWithFormat:@"Attempted to serialize invalid object: %@", jsonObject];
                NSDictionary *info = @{NSLocalizedDescriptionKey:msg};
                *error =  [NSError errorWithDomain:UAJSONSerializationErrorDomain
                                              code:UAJSONSerializationErrorCodeInvalidObject
                                          userInfo:info];
            }
            return nil;
        }
        NSData *data = [NSJSONSerialization dataWithJSONObject:jsonObject
                                                       options:opt
                                                         error:error];
        
        return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    } else {
        //this is a dirty hack but it works well. while NSJSONSerialization doesn't allow writing of
        //fragments, if we serialize the value in an array without pretty printing, and remove the
        //surrounding bracket characters, we get the equivalent result.
        NSString *arrayString = [self stringWithObject:@[jsonObject] options:0 acceptingFragments:NO error:error];
        return [arrayString substringWithRange:NSMakeRange(1, arrayString.length-2)];
    }
}

+ (id)objectWithString:(NSString *)jsonString {
    return [self objectWithString:jsonString options:NSJSONReadingMutableContainers];
}

+ (id)objectWithString:(NSString *)jsonString options:(NSJSONReadingOptions)opt {
    return [self objectWithString:jsonString options:opt error:nil];
}

+ (id)objectWithString:(NSString *)jsonString options:(NSJSONReadingOptions)opt error:(NSError **)error {
    if (!jsonString) {
        return nil;
    }
    return [NSJSONSerialization JSONObjectWithData: [jsonString dataUsingEncoding:NSUTF8StringEncoding]
                                           options: opt
                                             error: error];
}
@end


option參数说明.
     enum {
        NSJSONReadingMutableContainers = (1UL << 0),   //返回的容器是可变类型的(Array和Dictionary)
        NSJSONReadingMutableLeaves = (1UL << 1),     //返回的叶子NSString是可变类型的;
        NSJSONReadingAllowFragments = (1UL << 2)   //同意顶层的界面不是NSArray或NSDictionary;
    };
    typedef NSUInteger NSJSONReadingOptions;