iosobjective-cjsonsbjson

How to parse NSJsonDictionary objects in json file using SBJson4StreamParser


I'm new to iOS, I was able to write the NSDictionary objects into file like below example

{
"msg":"Hello",
"from":"X",
"date":"12/1/2014"
}
{
"msg":"new to IOS",
"from":"home",
"date":"23/2/2014"
}

I know it is an array of objects I need to be using NSArray, but I have prevented since my one NSDictionary object consumes lot of memory, I wanted to serialise and deserialize one object at a time. I came across SBJson4StreamParser internally does such functionality, but I was facing issues with implementation, I also tried with native NSJsonSeriailzation but options were limited for such type of parsing, can anyone help with this.


Solution

  • SBJson can help here, by reading the file chunkwise with an NSInputStream and feeding it into the parser like this:

    id parser = [SBJson4Parser multiRootParserWithBlock:block
                                           errorHandler:eh];
    
    id is = [NSInputStream inputStreamWithFileAtPath:filePath];
    [is open];
    
    // Buffer to read from the input stream
    uint8_t buf[1024];
    
    // Read from input stream until empty, or an error;
    // better error handling is left as an exercise for the reader
    while (0 > [is read:buffer maxLength: sizeof buffer]) {
        SBJson4ParserStatus status = [parser parse:data];
        NSLog(@"Status: %u",status);
        // Handle parser errors here
    }
    [is close];
    

    Note that you still have to read and parse the whole file to guarantee that you find a particular entry. There is no way to process just a specific entry this way.