开发者

NSString: EOL and rangeOfString issues

开发者 https://www.devze.com 2023-01-02 21:19 出处:网络
Could someone please tell me if I am missing something here... I am trying to parse individual JSON objects out of a d开发者_StackOverflow中文版ata stream. The data stream is buffered in a regular NSS

Could someone please tell me if I am missing something here... I am trying to parse individual JSON objects out of a d开发者_StackOverflow中文版ata stream. The data stream is buffered in a regular NSString, and the individual JSON objects are delineated by a EOL marker.

if([dataBuffer rangeOfString:@"\n"].location != NSNotFound) {
  NSString *tmp = [dataBuffer stringByReplacingOccurrencesOfString:@"\n" withString:@"NEWLINE"];
  NSLog(@"%@", tmp);
 }

The code above outputs "...}NEWLINE{..." as expected. But if I change the @"\n" in the if-statement above to @"}\n", I get nothing.


Why don't you use - (NSArray *)componentsSeparatedByString:(NSString *)separator? You can give it a separator of @"\n" and the result will be a convenient array of strings representing your individual JSON strings which you can then iterate over.

if([dataBuffer rangeOfString:@"\n"].location != NSNotFound) {
    NSArray* JSONstrings = [dataBuffer componentsSeparatedByString:@"\n"];

    for(NSString* oneString in JSONstrings)
    {
        // here's where you process individual JSON strings
    }
}

If you do mess with the terminating '}' you could make the JSON data invalid. Just break it up and pass it to the JSON library. There could easily be a trailing space after the '}' that is causing the problem you are observing.

0

精彩评论

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

关注公众号