File tree Expand file tree Collapse file tree 2 files changed +44
-0
lines changed
src/MongoDB.Bson/ObjectModel
tests/MongoDB.Bson.Tests/ObjectModel Expand file tree Collapse file tree 2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change @@ -386,6 +386,26 @@ public static BsonDocument Parse(string json)
386
386
}
387
387
}
388
388
389
+ /// <summary>
390
+ /// Tries to parse a JSON string and returns a value indicating whether it succeeded or failed.
391
+ /// </summary>
392
+ /// <param name="s">The JSON string.</param>
393
+ /// <param name="result">The result.</param>
394
+ /// <returns>Whether it succeeded or failed.</returns>
395
+ public static bool TryParse ( string s , out BsonDocument result )
396
+ {
397
+ try
398
+ {
399
+ result = Parse ( s ) ;
400
+ return true ;
401
+ }
402
+ catch
403
+ {
404
+ result = null ;
405
+ return false ;
406
+ }
407
+ }
408
+
389
409
// public methods
390
410
/// <summary>
391
411
/// Adds an element to the document.
Original file line number Diff line number Diff line change @@ -1373,6 +1373,30 @@ public void TestTryGetValue()
1373
1373
Assert . Equal ( 1 , value . AsInt32 ) ;
1374
1374
}
1375
1375
1376
+ [ Fact ]
1377
+ public void TestTryParse_success ( )
1378
+ {
1379
+ var s = "{ x : 1 }" ;
1380
+ BsonDocument result ;
1381
+
1382
+ var success = BsonDocument . TryParse ( s , out result ) ;
1383
+
1384
+ success . Should ( ) . BeTrue ( ) ;
1385
+ result . Should ( ) . Be ( new BsonDocument ( "x" , 1 ) ) ;
1386
+ }
1387
+
1388
+ [ Fact ]
1389
+ public void TestTryParse_failure ( )
1390
+ {
1391
+ var s = "{ ..." ;
1392
+ BsonDocument result ;
1393
+
1394
+ var success = BsonDocument . TryParse ( s , out result ) ;
1395
+
1396
+ success . Should ( ) . BeFalse ( ) ;
1397
+ result . Should ( ) . BeNull ( ) ;
1398
+ }
1399
+
1376
1400
private void AssertAreEqual ( string expected , byte [ ] actual )
1377
1401
{
1378
1402
StringBuilder sb = new StringBuilder ( ) ;
You can’t perform that action at this time.
0 commit comments