开发者

NSString from NSData -- Server returns NSData with leading nulls

开发者 https://www.devze.com 2023-04-05 06:16 出处:网络
I haven\'t seen a very clear answer on this one. For some reason I don\'t understand, the server I am receiving data from returns a JSON response with a lot (hundreds, maybe) of null bytes at the begi

I haven't seen a very clear answer on this one. For some reason I don't understand, the server I am receiving data from returns a JSON response with a lot (hundreds, maybe) of null bytes at the beginning.

When I use the following code, the string appears to be null:

    NSString* newStr = [[[NSString alloc] initWithData:dataToBeLoaded encoding:NSUTF8StringEncoding] autorelease];

This is apparently a common problem, but I haven't seen a clear answer on how to convert the NSData to an NSString.

Up until recently, I saw this problem with an intermediate NSString value, but it went away after I stripped a handful (but not hundreds) of characters off of the beginning and end. The NSString after stripping was perfectly fine, so I suppose the encoding method was not the problem.

Is there a built-in method that will do this properly? I have to imaging it would be more efficient that code I would write to go through byte-by-byte.

By the w开发者_StackOverflow社区ay, when I manually send the JSON request to the server in my browser, the response comes back as perfectly valid JSON, with no obvious problems showing up in the browser screen.

Any ideas what I should do? Thanks.


The data that is being returned from each server contains valid JSON (verified with JSON Lint in many instances). In one case, the return data is a javascript assignment statement containing a JSON object. In another case, it's simply a JSON object. In both cases, I know that the JSON object begins with a curly bracket.

So, to strip off all of the leading nulls, I use the code below. It seems that some methods treat the string data in an NSString like a C string, but other methods are aware that there is more to it, including an awareness of the length. Fortunately, rangeOfString and substringFromIndex look beyond the leading nulls.

NSString* newStr = [[[NSString alloc] initWithData:dataToBeLoaded encoding:NSUTF8StringEncoding] autorelease];

if (newStr == nil) return;

NSRange headRange = [newStr rangeOfString:@"{"];
NSString *stripped = [newStr substringFromIndex:headRange.location];
0

精彩评论

暂无评论...
验证码 换一张
取 消