您的位置:首页 > 移动开发 > Objective-C

SBJson库解析(二)NSObject+SBJson

2012-02-17 16:03 267 查看
一.NSObject+SBJson.h

1.把objc对象编码成json字符串

通过类别,为NSObject添加新方法:[NSObject JSONRepresentation]

@interface NSObject (NSObject_SBJsonWriting)
/**
虽然定义成NSObject的类别,但仅对NSArray和NSDictionary有效
返回:已编码的json对象,或nil
*/
- (NSString *)JSONRepresentation;
@end


2.把json对象解析为objc对象

通过类别,为NSString添加新方法:[NSString JSONValue]

@interface NSString (NSString_SBJsonParsing)
/**
返回:NSDictionary或NSArray对象,或nil
*/
- (id)JSONValue;
@end


二.NSObject+SBJson.m

导入头文件

#import "NSObject+SBJson.h"
#import "SBJsonWriter.h"
#import "SBJsonParser.h"


1.通过json编写器SBJsonWriter,的stringWithObject: 方法,实现[NSObject JSONRepresentation]编码逻辑

@implementation NSObject (NSObject_SBJsonWriting)

//objc2json
- (NSString *)JSONRepresentation {
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
NSString *json = [writer stringWithObject:self];
if (!json)
NSLog(@"-JSONRepresentation failed. Error is: %@", writer.error);
return json;
}

@end


2.通过json解析器SBJsonParser,的objectWithString: 方法,实现[NSString JSONValue]解析逻辑

@implementation NSString (NSString_SBJsonParsing)

//json2objc
- (id)JSONValue {
SBJsonParser *parser = [[SBJsonParser alloc] init];
id repr = [parser objectWithString:self];
if (!repr)
NSLog(@"-JSONValue failed. Error is: %@", parser.error);
return repr;
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: