#import <Foundation/Foundation.h>
@interface NSDictionary (Json)
//把網址上Json的數據,轉換成字典
+(NSDictionary*)dictionaryWithContentsOfURLString:(NSString*)urlAddress;
//把字典轉成Json對象
-(NSData*)toJSON;
@end
NSDictionary + Json .m
#import "NSDictionary+Json.h"
@implementation NSDictionary (Json)
// 直把远程的地址上Json数据转,换成Dictionary对象
+(NSDictionary*)dictionaryWithContentsOfURLString:(NSString*)urlAddress
{
// 请求远程数据,存放到NSData对象中
NSData* data =[NSDatadataWithContentsOfURL:[NSURLURLWithString: urlAddress]];
// 定义一个错误信息的对象
__autoreleasingNSError *error =nil;
// 序列化字符串
id result =[NSJSONSerialization JSONObjectWithData:data
options:kNilOptions error:&error];
if(error !=nil)
return nil;
return result;
}
// 把当前的Dictionary对象,转成Json对象
-(NSData*)toJSON{
NSError *error =nil;
// 把当前的Dictionary对象转换成字符串
id result =[NSJSONSerializationdataWithJSONObject:self
options:kNilOptions error:&error];
if(error !=nil)
return nil;
return result;
}
@end
沒有留言:
張貼留言