Error deserializing json stream

江枫思渺然 提交于 2019-12-08 07:10:57

问题


I have an NSInputStream *inputStream receiving small JSON objects from a network connection. If I read the stream to a buffer like so:

NSError *err = nil;
uint8_t buffer[1024];
NSMutableData *data = [[NSMutableData alloc] init];
while ([inputStream hasBytesAvailable]) {
    int const len = [inputStream read:buffer maxLength:sizeof(buffer)];
    if (0 < len) {
        [data appendBytes:buffer length:len];
    }
}
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];

then I get the JSON I expect; but this is very brittle, as it assumes that there is exactly one JSON object to read. With this scheme, I could end up trying to deserialize {"cheese":17}{"ch, which is obviously invalid. I'd rather use

NSError *err = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithStream:inputStream options:0 error:&err];

but, but stepping through with the debugger, I discovered that this last line does not return, and logs no error! What's the right approach?

来源:https://stackoverflow.com/questions/18362889/error-deserializing-json-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!