记录

//将字典转成json字符串

+ (NSString*)convertToJSONData:(id)infoDict

{

NSError*error;

NSData*jsonData = [NSJSONSerializationdataWithJSONObject:infoDict

options:NSJSONWritingPrettyPrinted// Pass 0 if you don't care about the readability of the generated string

error:&error];

NSString*jsonString =@"";

if(! jsonData)

{

NSLog(@"Got an error: %@", error);

}else

{

jsonString = [[NSStringalloc]initWithData:jsonDataencoding:NSUTF8StringEncoding];

}

jsonString = [jsonStringstringByTrimmingCharactersInSet:[NSCharacterSetwhitespaceAndNewlineCharacterSet]];//去除掉首尾的空白字符和换行字符

[jsonStringstringByReplacingOccurrencesOfString:@"\n"withString:@""];

returnjsonString;

}

//截取最大长度的字符串不够的补全

+(NSString*)finalText:(NSString*)string

{

NSString*string1=string;

NSStringEncodingenc =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);

NSData*data = [string1dataUsingEncoding:enc];

if(data.length>12) {

data = [datasubdataWithRange:NSMakeRange(0,12)];

string1 = [[NSStringalloc]initWithData:dataencoding:enc];

if(!string1) {

data = [datasubdataWithRange:NSMakeRange(0,12-1)];

string1 = [[NSStringalloc]initWithData:dataencoding:enc];

}

string1 = [string1stringByAppendingString:@""];

returnstring1;

}

else

{

for(inta=0; a<12-data.length; a++)

{

string=[NSStringstringWithFormat:@"%@%s",string," "];

}

returnstring;

}

}


#pragma mark - 截取字符串

+(NSString*)finalText:(NSString*)string maxChar:(int)maxChar

{

NSString*string1=string;

NSStringEncodingenc =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);

NSData*data = [string1dataUsingEncoding:enc];

if(data.length> maxChar) {

data = [datasubdataWithRange:NSMakeRange(0, maxChar)];

string1 = [[NSStringalloc]initWithData:dataencoding:enc];

if(!string1) {

data = [datasubdataWithRange:NSMakeRange(0, maxChar -1)];

string1 = [[NSStringalloc]initWithData:dataencoding:enc];

}

string1 = [string1stringByAppendingString:@""];

}

returnstring1;

}

你可能感兴趣的:(记录)