iOS

NSString+JSON - iOS

2018-09-18  本文已影响67人  survivorsfyh

日常开发中常用的一个相互转换的方法;

直接创建对应的类,引用如下方法即可实现;

具体 code 如下:

声明:

#import <Foundation/Foundation.h>
 
@interface NSString (JSON)
 
- (id)jsonObject;
 
/** dic -> json*/
- (NSString *)dictionaryToJson:(NSDictionary *)dic;
 
@end

实现:

#import "NSString+JSON.h"
 
extern void dictionaryFilterNullNode(NSMutableDictionary*);
extern void arrayFilterNullNode(NSMutableArray*);
 
void inline dictionaryFilterNullNode(NSMutableDictionary *dic) {
    NSMutableArray *deleteKeys = [NSMutableArray array];
    [[dic allKeys] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        id value = [dic objectForKey:obj];
        if ([value isKindOfClass:[NSNull class]]) {
            [deleteKeys addObject:obj];
        } else if([value isKindOfClass:[NSMutableArray class]]) {
            arrayFilterNullNode(value);
        } else if([value isKindOfClass:[NSMutableDictionary class]]) {
            dictionaryFilterNullNode(value);
        }
    }];
    [deleteKeys enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [dic removeObjectForKey:obj];
    }];    
    deleteKeys;
}
 
void inline arrayFilterNullNode(NSMutableArray *array) {
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([obj isKindOfClass:[NSMutableDictionary class]]) {
            dictionaryFilterNullNode(obj);
        }
    }];
}
 
@implementation NSString (JSON)
- (id)jsonObject {
    NSError *error = nil;
    id result = [NSJSONSerialization JSONObjectWithData:[self dataUsingEncoding:NSUTF8StringEncoding]
                                                options:NSJSONReadingMutableContainers
                                                  error:&error];
    
    if (error || [NSJSONSerialization isValidJSONObject:result] == NO)
    {
        return self;
    }
    
    if ([result isKindOfClass:[NSMutableArray class]]) {
        arrayFilterNullNode(result);
        
    } else if([result isKindOfClass:[NSMutableDictionary class]]) {
        dictionaryFilterNullNode(result);
        
    }else if ([result isKindOfClass:[NSNull class]]){
//        result;
        NSLog(@"----->%@",result);
        return self;
    }
    
    return result;
}
 
//dic -> json
- (NSString *)dictionaryToJson:(NSDictionary *)dic {
    NSError *error = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
 
 
 
@end

NSDictionary+JSON - iOS 机票如下: NSDictionary+JSON - iOS

以上便是此次分享的内容,希望能对大家有所帮助!

上一篇下一篇

猜你喜欢

热点阅读