Convert a dictionary or array into JSON data or a string
Source:
Nsdictionary+json.h and nsdictionary+json.m
////Nsdictionary+json.h//Category////Created by youxianming on 15-2-09.//Copyright (c) 2014 youxianming. All rights reserved.//#import<Foundation/Foundation.h>@interfacensdictionary (JSON)/** * Convert to JSON string (no readability) * * @return JSON string*/-(NSString *) tojsonstring;/** * Convert to JSON string (readable) * * @return JSON string*/-(NSString *) toreadablejsonstring;/** * Convert to JSON data * * @return JSON data*/-(NSData *) Tojsondata;@end
////nsdictionary+json.m//Category////Created by youxianming on 15-2-09.//Copyright (c) 2014 youxianming. All rights reserved.//#import "Nsdictionary+json.h"@implementationnsdictionary (JSON)-(NSString *) tojsonstring {nsdata*data =[Nsjsonserialization datawithjsonobject:self OPTIONS:NSJSONREADINGM Utableleaves|nsjsonreadingallowfragments Error:nil]; if(Data = =Nil) { returnNil; } nsstring*string=[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; return string;}-(NSString *) toreadablejsonstring {nsdata*data =[Nsjsonserialization datawithjsonobject:self OPTIONS:NSJSONWRITINGP Rettyprinted Error:nil]; if(Data = =Nil) { returnNil; } nsstring*string=[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; return string;}-(NSData *) Tojsondata {nsdata*data =[Nsjsonserialization datawithjsonobject:self OPTIONS:NSJSONWRITINGP Rettyprinted Error:nil]; returndata;}@end
Nsarray+json.h and nsarray+json.m
////Nsarray+json.h//Category////Created by youxianming on 15-2-09.//Copyright (c) 2014 youxianming. All rights reserved.//#import<Foundation/Foundation.h>@interfaceNsarray (JSON)/** * Convert to JSON string (no readability) * * @return JSON string*/-(NSString *) tojsonstring;/** * Convert to JSON string (readable) * * @return JSON string*/-(NSString *) toreadablejsonstring;/** * Convert to JSON data * * @return JSON data*/-(NSData *) Tojsondata;@end
////nsarray+json.m//Category////Created by youxianming on 15-2-09.//Copyright (c) 2014 youxianming. All rights reserved.//#import "Nsarray+json.h"@implementationNsarray (JSON)-(NSString *) tojsonstring {nsdata*data =[Nsjsonserialization datawithjsonobject:self OPTIONS:NSJSONREADINGM Utableleaves|nsjsonreadingallowfragments Error:nil]; if(Data = =Nil) { returnNil; } nsstring*string=[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; return string;}-(NSString *) toreadablejsonstring {nsdata*data =[Nsjsonserialization datawithjsonobject:self OPTIONS:NSJSONWRITINGP Rettyprinted Error:nil]; if(Data = =Nil) { returnNil; } nsstring*string=[[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]; return string;}-(NSData *) Tojsondata {nsdata*data =[Nsjsonserialization datawithjsonobject:self OPTIONS:NSJSONWRITINGP Rettyprinted Error:nil]; returndata;}@end
Use:
Convert a dictionary or array into JSON data or a string