skip to Main Content

I’m using an API and I’m not 100% sure of the types (and that can’t be changed, unfortunately). I’m using the method ‘DeserializeObject’ from the NewtonSoft.Json namespace ‘JsonConvert’ type.

Is there a way to deserialize the things that I have defined and skip the errors?

For example, let’s say I have the following JSON object:

{
  "name": "John Smith",
  "age": 30,
  "city": "New York"
}

And the C# object I’ll deserialize it into will be:

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Root
{
    public string name { get; set; }
    public int age { get; set; }
    public string city { get; set; }
}

However, let’s say the age comes as a string, but I don’t know it may come as a string and thus I can’t use the JsonConverter method. That’d end in an error.

Is there a way to handle the error and deserialize the name property and the city property?

2

Answers


  1. Try using this code example

    string json = "{ invalid json }";
    
    var settings = new JsonSerializerSettings();
    settings.Error = (sender, args) => {
        // Handle the error here
        // For example, you could log the error or ignore it
        args.ErrorContext.Handled = true;
    };
    
    try
    {
        var obj = JsonConvert.DeserializeObject<MyClass>(json, settings);
    }
    catch (JsonException ex)
    {
        // Handle the exception here
        // For example, you could log the exception or display an error message
    }
    
    Login or Signup to reply.
  2. If you use Newtonsoft.Json, in this case "age":"30" will be working too

    Root root = JsonConvert.DeserializeObject<Root>(json); // No error
    

    But you can’t create one code to held properly the exceptions for all properties. For example, in the case "age":"" or "age":null , I would create a json costructor

    public class Person
    {
        public string name { get; set; }
        public int age { get; set; }
        public string city { get; set; }
        
        [JsonConstructor]
        public Person(JToken age)
        {
            if (age.Type == JTokenType.String)
            {
                if (int.TryParse((string)age, out var ageInt)) this.age = ageInt;
                else this.age = -1;
    
                // or if you make c# age property nullable - int?
                //else age = null;
            }
            else if (!age.HasValues) this.age = -1;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search