I know i can use an external library(newtonsoft) with a try/catch to check if a string is valid json structure. I do not want to deserialize to an object (since the json can be one or many properties) point is to just make sure its valid json.
I would prefer to use the System.Text.Json but not sure what would be the best, TryParseValue, JsonDocument, etc
If your JSON is in a string and you are using System.Text.Json then probably the best way to check the JSON is well-formed would be to use JsonDocument.Parse. For example:
public static class StringExtensions
{
public static bool IsJson(this string source)
{
if (source == null)
return false;
try
{
using (JsonDocument doc = JsonDocument.Parse(source))
{
// dispose any created doc
}
return true;
}
catch (JsonException)
{
return false;
}
}
}
An small improvement in @bytedev answer, disposing JsonDocument based on Microsoft JsonDocument remark:
This class utilizes resources from pooled memory to minimize the impact of the garbage collector (GC) in high-usage scenarios. Failure to properly dispose this object will result in the memory not being returned to the pool, which will increase GC impact across various parts of the framework
public static bool IsJsonValid(this string json)
{
if (string.IsNullOrWhiteSpace(json))
return false;
try
{
using var jsonDoc = JsonDocument.Parse(json);
return true;
}
catch (JsonException)
{
return false;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With