Handle bad JSON data without crashing

Summary:
public
NSJSONSerialization throws an exception when it encounters bad JSON data, including NaN values, which may not be a programming error.

This diff adds code to catch those exceptions and convert to an error. Also, if no error handling is in place, RCTJSONStringify will now display a redbox, and attempt to recover by sanitizing the JSON data and retrying.

Reviewed By: javache

Differential Revision: D2854778

fb-gh-sync-id: 18e6990af0d91083496d6a0b75c31a94ed9454a5
This commit is contained in:
Nick Lockwood
2016-01-26 06:12:48 -08:00
committed by facebook-github-bot-3
parent 1edcf4c6ac
commit 7419a82bd7
5 changed files with 88 additions and 14 deletions

View File

@@ -78,4 +78,35 @@
XCTAssertEqualObjects(obj, RCTJSONParse(json, NULL));
}
- (void)testNotJSONSerializable
{
NSDictionary<NSString *, id> *obj = @{@"foo": [NSDate date]};
NSString *json = @"{\"foo\":null}";
XCTAssertEqualObjects(json, RCTJSONStringify(obj, NULL));
}
- (void)testNaN
{
NSDictionary<NSString *, id> *obj = @{@"foo": @(NAN)};
NSString *json = @"{\"foo\":0}";
XCTAssertEqualObjects(json, RCTJSONStringify(obj, NULL));
}
- (void)testNotUTF8Convertible
{
//see https://gist.github.com/0xced/56035d2f57254cf518b5
NSString *string = [[NSString alloc] initWithBytes:"\xd8\x00" length:2 encoding:NSUTF16StringEncoding];
NSDictionary<NSString *, id> *obj = @{@"foo": string};
NSString *json = @"{\"foo\":null}";
XCTAssertEqualObjects(json, RCTJSONStringify(obj, NULL));
}
- (void)testErrorPointer
{
NSDictionary<NSString *, id> *obj = @{@"foo": [NSDate date]};
NSError *error;
XCTAssertNil(RCTJSONStringify(obj, &error));
XCTAssertNotNil(error);
}
@end