JsonStr 与 dic 相互转换 --》笔记
+ (NSString*)dictionaryToJson:(NSDictionary*)dic {
if ([NSJSONSerialization isValidJSONObject:dic]) {
NSError*error =nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
if(error) {
DebugLog(@"[%@] Post Json Error: %@", [self class], dic);
returnnil;
}
NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
DebugLog(@"CustomElemCmd content is %@", dic);
returnjsonStr;
}else{
DebugLog(@"[%@] CustomElemCmd is not valid: %@", [self class], dic);
returnnil;
}
}
+ (NSDictionary*)jsonToDic:(NSString*)jsonStr{
if(!jsonStr) {
returnnil;
}
NSError*error =nil;
NSData *jsonData = [[NSData alloc] initWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
if(error) {
returnnil;
}
returndic;
}
// 检索字典,格式化字段
+ (NSString*)formatValueWithDic:(NSDictionary*)dic AndKey:(NSString*)key {
if (!dic || ![dic isKindOfClass:[NSDictionary class]]) {
return@"";
}
iddata1 = [dicobjectForKey:key];
if(data1) {
if ([data1 isKindOfClass:[NSString class]]) {
return(NSString*)data1;
}else{
@try{
NSString*str = [NSStringstringWithFormat:@"%@", data1];
if([strcontainsString:@"null"]) {
return@"";
}
returnstr;
}
@catch(NSException *exception) {
return@"";
}
}
}else{
return@"";
}
}
网友评论