Sunday, May 12, 2013

NSJSONSerialization writeJSONObject toStream options error example ios


writeJSONObject: toStream: options: error:

Writes a given JSON object to a stream.
+ (NSInteger)writeJSONObject:(id)obj toStream:(NSOutputStream *)stream options:(NSJSONWritingOptions)opt error:(NSError **)error
Parameters
obj
The object to write to stream.
stream
The stream to which to write.
The stream should be opened and configured.( NSJSONSerialization writeJSONObject toStream options error example )
opt
Options for writing the JSON data.
See “NSJSONWritingOptions” for possible values. Pass 0 to specify no options.
error
If an error occurs, upon return contains an NSError object that describes the problem.
Return Value
The number of bytes written to the stream, or 0 if an error occurs.
( NSJSONSerialization writeJSONObject toStream options error example )
NSString *fileName = @"myJsonDict.dat"; // probably somewhere in 'Documents'
NSDictionary *dict = @{ @"key" : @"value" };

NSOutputStream *os = [[NSOutputStream alloc] initToFileAtPath:fileName append:NO];

[os open];
[NSJSONSerialization writeJSONObject:dict toStream:os options:0 error:nil];
[os close];

// reading back in...
NSInputStream *is = [[NSInputStream alloc] initWithFileAtPath:fileName];

[is open];
NSDictionary *readDict = [NSJSONSerialization JSONObjectWithStream:is options:0 error:nil];
[is close];

NSLog(@"%@", readDict);
( NSJSONSerialization writeJSONObject toStream options error example )
NSError *error = nil;
NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:filepath append:yesOrNo];
[outputStream open];

[NSJSONSerialization writeJSONObject :nsDicOrNSArrayObject 
                            toStream :outputStream 
                             options :0 
                               error :&error];
[outputStream close];