2929
3030#if NET || NETSTANDARD2_0_OR_GREATER
3131using System . Text . Encodings . Web ;
32+ using System . Text . Json ;
3233#endif
3334
3435using System . Text . RegularExpressions ;
@@ -1373,6 +1374,7 @@ public static string AddQueryString(this string url, string name, string value)
13731374 return url . AddQueryString ( name + "=" + UrlEncoder . Default . Encode ( value . IfNullThenEmpty ( ) ) ) ;
13741375 }
13751376#endif
1377+
13761378 /// <summary>
13771379 /// Add hash fragment to URL
13781380 /// </summary>
@@ -1494,5 +1496,83 @@ public static string TrimSuffix(this string source, string suffix, StringCompari
14941496 /// <returns></returns>
14951497 /// <remarks></remarks>
14961498 public static string IfNullThenEmpty ( this string source ) => source ?? string . Empty ;
1499+
1500+ #if NET || NETSTANDARD2_0_OR_GREATER
1501+
1502+ /// <summary>
1503+ /// Check if provided source is as valid JSON
1504+ /// </summary>
1505+ /// <param name="source">Source string</param>
1506+ /// <returns></returns>
1507+ /// <remarks></remarks>
1508+ public static bool IsValidJson ( this string source )
1509+ {
1510+ try
1511+ {
1512+ if ( source . IsMissing ( ) ) return false ;
1513+ if ( ( source . TrimIfNotNull ( ) . StartsWith ( "{" ) && source . TrimIfNotNull ( ) . EndsWith ( "}" ) ) ||
1514+ ( source . TrimIfNotNull ( ) . StartsWith ( "[" ) && source . TrimIfNotNull ( ) . EndsWith ( "]" ) ) )
1515+ {
1516+ using var jsonDoc = JsonDocument . Parse ( source ) ;
1517+
1518+ return true ;
1519+ }
1520+ else return false ;
1521+ }
1522+ catch
1523+ {
1524+ return false ;
1525+ }
1526+ }
1527+
1528+ /// <summary>
1529+ /// Check if provided source is as valid JSON object
1530+ /// </summary>
1531+ /// <param name="source">Source string</param>
1532+ /// <returns></returns>
1533+ /// <remarks></remarks>
1534+ public static bool IsValidJsonObject ( this string source )
1535+ {
1536+ try
1537+ {
1538+ if ( source . IsMissing ( ) ) return false ;
1539+ if ( source . TrimIfNotNull ( ) . StartsWith ( "{" )
1540+ && source . TrimIfNotNull ( ) . EndsWith ( "}" ) )
1541+ {
1542+ return source . IsValidJson ( ) ;
1543+ }
1544+ else return false ;
1545+ }
1546+ catch
1547+ {
1548+ return false ;
1549+ }
1550+ }
1551+
1552+ /// <summary>
1553+ /// Check if provided source is as valid JSON array
1554+ /// </summary>
1555+ /// <param name="source">Source string</param>
1556+ /// <returns></returns>
1557+ /// <remarks></remarks>
1558+ public static bool IsValidJsonArray ( this string source )
1559+ {
1560+ try
1561+ {
1562+ if ( source . IsMissing ( ) ) return false ;
1563+ if ( source . TrimIfNotNull ( ) . StartsWith ( "[" )
1564+ && source . TrimIfNotNull ( ) . EndsWith ( "]" ) )
1565+ {
1566+ return source . IsValidJson ( ) ;
1567+ }
1568+ else return false ;
1569+ }
1570+ catch
1571+ {
1572+ return false ;
1573+ }
1574+ }
1575+
1576+ #endif
14971577 }
14981578}
0 commit comments