Below is the default code to parse a JsonArray, which works totally fine if there is of course no error or typo in the Json string:
public class Person
{
public int Id { get; set; }
public required string Name { get; set; }
}
Program code:
var jsonString = @"
[
{ ""Id"": 1, ""Name"": ""name1"" },
{ ""Id"": 2, ""Name"": ""name2"" },
{ ""Id"": 3, ""NameX"": ""name3"" },
{ ""Id"": 4, ""Name"": ""name4"" },
{ ""Id"": 5, ""Name"": ""name5"" }
]
";
List<Person> people = JsonSerializer.Deserialize<List<Person>>(jsonString) ?? [];
Console.WriteLine(people.Count);
But notice that in the jsonString
, there is unfortunately a typo. Of course, this results in a runtime error. It is possible to wrap the Deserialize<>
in a try-catch
, but then I have 0 people in my people
array.
This is a simplification of the situation I have of course, in my case I get the json from an external source. (Assume it is not possible to skip the required
attribute for string Name
in this example)
How can I change this code so that I basically have a TryDeserialize<>
? I would like to parse every correct object, and skip (and log if that is possible) all the objects that aren’t correct? So that my final people array has 4 people in it (ids 1,2,4,5)?
2
Answers
For such task you would need to implement custom JSON converter for list of
Person
objects.Here’s example implementation:
And then the usage:
One option would be to use a JsonReader instead.