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






转载于:https://www.cnblogs.com/xiaodao/archive/2012/02/17/2355946.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值