Click here to Skip to main content
15,895,709 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello, so long story short I have a web app, which uses Json deserialization in order to display information about products:

C#
var ProductInfo = JsonConvert.DeserializeObject<Product>(Product.CertificateFieldsHeader);


I want to avoid situation in which if deserialization fails (for example JSON is invalid), user will get a 500 error.

What I have tried:

First thing which came to my mind was simply throwing it into try catch block:

C#
try
       {
          var ProductInfo = JsonConvert.DeserializeObject<Product>(Product.CertificateFieldsHeader);

       }
       catch (JsonException jsonException)
       {
                   _logger.LogInformation(jsonException);

       }

...but that solution didn't seem to be very elegant.


I have also thought about creating an extension method, for example:
C#
public static bool TryParseJson<T>(this string obj, out T result)
{
    try
    {
        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.MissingMemberHandling = MissingMemberHandling.Error;

        result = JsonConvert.DeserializeObject<T>(obj, settings);
        return true;
    }
    catch (Exception)
    {
        result = default(T);
        return false;
    }
}


But that method wasn't catching any errors when I tested it. How should I approach the problem? Just stick to simple try catch block?
Posted
Updated 30-Oct-22 3:50am
v2
Comments
[no name] 29-Oct-22 19:26pm    
You should pre-scan "product information" before loading it; then you wouldn't have any errors.

1 solution

Your best option is to generate the classes from the JSON data. This will do an initial check for malformed data. I like to use: JSON Utils: Generate C#, VB.Net, SQL TAble and Java from JSON[^]. There are others mentioned in the link below.

As for working with Json data, I have written 2 comprehensive articles that will help with this and more:
1. Working with Newtonsoft.Json in C# & VB[^]
2. Working with System.Text.Json in C#[^]

I hope this helps.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900