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
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- SBJson库解析(二)NSObject+SBJson
- SBJson库解析(十)SBJsonStreamParserAccumulator
- NSObject头文件解析 / 消息机制 / Runtime解读 (一)
- SBJson库解析(八)SBJsonStreamParserAdapter
- iOS源码解析—YYModel(NSObject+YYModel)
- JSON之解析通过TouchJSON\SBJSON\JSONKit\NSJSONSeriliz...
- IOS问题汇总:2015-1-8 SBJson解析时报错—json文件字符非法
- SBJson库解析(七)SBJsonStreamParser
- iOS json解析的几种方法 NSJSONSerialization,JSONKit,SBJson ,TouchJson
- sbjson解析json数据遇到JSONValue failed. Error is: Illegal start of token [Ô]解决办法
- SBJson库解析(六)SBJsonParser
- iOS SBJSON解析错误 Unescaped control character [0x09]
- Objective-C Runtime 解析(二)——NSObject的load与initialize方法
- ios 中使用SBJson拼接和解析json
- SBJson库解析(四)SBJsonStreamWriter
- 我的SBJson来生成和解析JSON串的代码
- ASIHttpRequest+SBJson完成Http请求,以及json数据解析
- SBJson库解析(五)SBJsonStreamWriterAccumulator
- IOS——SBJSON解析错误 Unescaped control character [0x09]
- SBJson库解析(四)SBJsonStreamWriter