SBJson库解析(二)NSObject+SBJson

一.NSObject+SBJson.h

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

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

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

2.json对象解析为objc对象

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

1 @interface NSString (NSString_SBJsonParsing)
2 /**
3 返回:NSDictionary或NSArray对象,或nil
4 */
5 - (id)JSONValue;
6 @end

二.NSObject+SBJson.m

导入头文件

1 #import "NSObject+SBJson.h"
2 #import "SBJsonWriter.h"
3 #import "SBJsonParser.h"

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

 1 @implementation NSObject (NSObject_SBJsonWriting)
2
3 //objc2json
4 - (NSString *)JSONRepresentation {
5 SBJsonWriter *writer = [[SBJsonWriter alloc] init];
6 NSString *json = [writer stringWithObject:self];
7 if (!json)
8 NSLog(@"-JSONRepresentation failed. Error is: %@", writer.error);
9 return json;
10 }
11
12 @end

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

 

 1 @implementation NSString (NSString_SBJsonParsing)
2
3 //json2objc
4 - (id)JSONValue {
5 SBJsonParser *parser = [[SBJsonParser alloc] init];
6 id repr = [parser objectWithString:self];
7 if (!repr)
8 NSLog(@"-JSONValue failed. Error is: %@", parser.error);
9 return repr;
10 }
11
12 @end






posted @ 2012-02-17 16:03  月光的尽头  阅读(2833)  评论(0编辑  收藏  举报