2

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?

felipebubu
  • 131
  • 7
  • 1
    Have you looked at this? https://www.newtonsoft.com/json/help/html/serializationerrorhandling.htm – cmos Jan 05 '23 at 09:55
  • https://docs.microsoft.com/de-de/dotnet/api/system.text.json.serialization.jsonnumberhandling – Oliver Jan 05 '23 at 10:01
  • this can help you https://stackoverflow.com/questions/26107656/ignore-parsing-errors-during-json-net-data-parsing – szwarcus Jan 05 '23 at 10:26

2 Answers2

1

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;
    }
}
Serge
  • 40,935
  • 4
  • 18
  • 45
0

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
}