标签:
最近在使用 ASIHTTPRequest 的过程遇到一个问题,ASI 将 返回的 data 转换成了string,然后就在 dic 前面多了一些字符,导致 string 成了一个不是有效的 json 串。
// Call this method to get the received data as an NSString. Don‘t use for binary data! - (NSString *)responseString { NSData *data = [self responseData]; if (!data) { return nil; } return [[[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:[self responseEncoding]] autorelease]; }
如果直接调用 NSData *data = [self responseData]; 是没有错的,一旦调用 - (NSString *)responseString 就回出现这种情况
为此呢,不得已又写了一个方法将多余的字符删除掉...
1 - (NSString *)jsonStringProcessingWithString:(NSString *)jsonString{ 2 NSString *resultJsonString = @""; 3 4 int head = 0; 5 int trail = jsonString.length; 6 7 for (int i=0; i<jsonString.length; i++) { 8 unichar ch = [jsonString characterAtIndex:i]; 9 if (ch == 0x007B) { 10 head = i; 11 break; 12 } 13 } 14 for (int i=jsonString.length-1; i>0; i--) { 15 unichar ch = [jsonString characterAtIndex:i]; 16 if (ch == 0x007D) { 17 trail = i; 18 break; 19 } 20 } 21 22 NSRange range = NSMakeRange(head, trail-head+1); 23 resultJsonString = [jsonString substringWithRange:range]; 24 25 return resultJsonString; 26 }
然后就木有问题了...
标签:
原文地址:http://www.cnblogs.com/chenjungang/p/4223572.html