views:

50

answers:

1

Could someone please tell me if I am missing something here... I am trying to parse individual JSON objects out of a data 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.

+1  A: 

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.

Adam Eberbach
The problem is that that only works if none of the values in the json object contain end of line markers. Otherwise you end up splitting objects apart.The problem is that the '}' turns up at ([dataBuffer rangeOfString:@"\n"].location - 2) although there is no space. For some reason the \ and n each get counted as characters in the comparison. I ended up looping through the whole string and checking each individual character, but I am still hoping that there is a better way.
carloe
'{' and '}' must balance in JSON - so you could count, and if not balanced, treat the following arrays as a stream. Examine them to find how many arrays are required to complete the data and append/remove until you have just an array of correct strings.
Adam Eberbach