关闭

轻量级的将NSDictionary, NSArray, NSString转换为JSON格式字符串的NSString类目

231人阅读 评论(0) 收藏 举报
分类:

//

//  NSString+JSON.h

//  WSPhnixPurfier

//

//  Created by Joy on 13-9-4.

//  Copyright (c) 2013 Joy. All rights reserved.

//


#import


@interface NSString (JSON)


+(NSString *) jsonStringWithDictionary:(NSDictionary *)dictionary;

+(NSString *) jsonStringWithArray:(NSArray *)array;

+(NSString *) jsonStringWithString:(NSString *) string;

+(NSString *) jsonStringWithObject:(id) object;


@end



 

//

//  NSString+JSON.m

//  WSPhnixPurfier

//

//  Created by Joy on 13-9-4.

//  Copyright (c) 2013 Joy. All rights reserved.

//


#import "NSString+JSON.h"


@implementation NSString (JSON)


+(NSString *) jsonStringWithString:(NSString *) string{

    return [NSString stringWithFormat:@""%@"",

            [[string stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"]stringByReplacingOccurrencesOfString:@"""withString:@"\\""]

            ];

}


+(NSString *) jsonStringWithArray:(NSArray *)array{

    NSMutableString *reString = [NSMutableString string];

    [reString appendString:@"["];

    NSMutableArray *values = [NSMutableArray array];

    for (id valueObj in array) {

        NSString *value = [NSString jsonStringWithObject:valueObj];

        if (value) {

            [values addObject:[NSString stringWithFormat:@"%@",value]];

        }

    }

    [reString appendFormat:@"%@",[values componentsJoinedByString:@","]];

    [reString appendString:@"]"];

    return reString;

}


+(NSString *) jsonStringWithDictionary:(NSDictionary *)dictionary{

    NSArray *keys = [dictionary allKeys];

    NSMutableString *reString = [NSMutableString string];

    [reString appendString:@"{"];

    NSMutableArray *keyValues = [NSMutableArray array];

    for (int i=0; i<[keys count]; i++) {

        NSString *name = [keys objectAtIndex:i];

        id valueObj = [dictionary objectForKey:name];

        NSString *value = [NSString jsonStringWithObject:valueObj];

        if (value) {

            [keyValues addObject:[NSString stringWithFormat:@""%@":%@",name,value]];

        }

    }

    [reString appendFormat:@"%@",[keyValues componentsJoinedByString:@","]];

    [reString appendString:@"}"];

    return reString;

}


+(NSString *) jsonStringWithObject:(id) object{

    NSString *value = nil;

    if (!object) {

        return value;

    }

    if ([object isKindOfClass:[NSString class]]) {

        value = [NSString jsonStringWithString:object];

    }else if([object isKindOfClass:[NSDictionary class]]){

        value = [NSString jsonStringWithDictionary:object];

    }else if([object isKindOfClass:[NSArray class]]){

        value = [NSString jsonStringWithArray:object];

    }

    return value;

}


@end

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:275144次
    • 积分:7273
    • 等级:
    • 排名:第3054名
    • 原创:471篇
    • 转载:68篇
    • 译文:2篇
    • 评论:27条
    最新评论