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

SBJson库解析(二)NSObject+SBJson

2020-02-01 21:26 1381 查看

一.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

  • 点赞
  • 收藏
  • 分享
  • 文章举报
aa631555244 发布了0 篇原创文章 · 获赞 0 · 访问量 528 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: