/*!
* 将字典或者数组转化为JSON串
*
* @param theData <#theData description#>
*
* @return <#return value description#>
*/
+ (NSString *)toJSONData:(id)theData{
NSString * jsonString = @"";
if (theData != nil) {
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
options:NSJSONWritingPrettyPrinted
error:nil];
if ([jsonData length] != 0){
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
return jsonString;
}
/*!
* 将JSON串转化为字典或者数组
*
* @param jsonData <#jsonData description#>
*
* @return <#return value description#>
*/
+ (id)toArrayOrNSDictionary:(NSString *)jsonData{
if (jsonData != nil) {
NSData* data = [jsonData dataUsingEncoding:NSUTF8StringEncoding];
id jsonObject = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:nil];
if (jsonObject != nil){
return jsonObject;
}else{
// 解析错误
return nil;
}
}
return nil;
}
/*!
* 对象序列成字典
*
* @param obj 需要序列化的对象
*
* @return 字典
*/
+ (NSDictionary*)getDictionaryFromObject:(id)obj
{
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
unsigned int propsCount;
objc_property_t *props = class_copyPropertyList([obj class], &propsCount);
for(int i = 0;i < propsCount; i++) {
objc_property_t prop = props[i];
id value = nil;
@try {
NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];
value = [self getObjectInternal:[obj valueForKey:propName]];
if(value != nil) {
[dic setObject:value forKey:propName];
}
}
@catch (NSException *exception) {
NSLog(@"%@",exception);
}
}
free(props);
return dic;
}
+ (id)getObjectInternal:(id)obj
{
if(!obj
|| [obj isKindOfClass:[NSString class]]
|| [obj isKindOfClass:[NSNumber class]]
|| [obj isKindOfClass:[NSNull class]]) {
return obj;
}
if([obj isKindOfClass:[NSArray class]]) {
NSArray *objarr = obj;
NSMutableArray *arr = [NSMutableArray arrayWithCapacity:objarr.count];
for(int i = 0;i < objarr.count; i++) {
[arr setObject:[self getObjectInternal:[objarr objectAtIndex:i]] atIndexedSubscript:i];
}
return arr;
}
if([obj isKindOfClass:[NSDictionary class]]) {
NSDictionary *objdic = obj;
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];
for(NSString *key in objdic.allKeys) {
[dic setObject:[self getObjectInternal:[objdic objectForKey:key]] forKey:key];
}
return dic;
}
return [self getDictionaryFromObject:obj];
}