Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deserialize Json array in .NET7 project gives error

I’m feeling stupid, because I get an error and cannot figure out why.

Error:

System.Text.Json.JsonException: ‘The JSON value could not be converted to System.Collections.Generic.List`1[Helpspot.CL.Model.Event]. Path: $ | LineNumber: 0 |

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Test class:

class Event {
    public int Year { get; set; }
}

Test code:

var json = @"{""event"":[{""Year"":1945},{""Year"":1527}]}";
var list = JsonSerializer.Deserialize<List<Event>>(json);

It does work when I deserialize one object:

var json = @"{""Year"":1945}";
var obj = JsonSerializer.Deserialize<Event>(json);

>Solution :

The following JSON:

var json = @"{""event"":[{""Year"":1945},{""Year"":1527}]}";

Represents a JSON object with property event containing a collection of events, so either fix the JSON (var json = @"[{""Year"":1945},{""Year"":1527}]";)
or add another type to represent your JSON correctly (another option would by "dynamic" deserialization with the JSON DOM APIs):

var obj = JsonSerializer.Deserialize<Root>(json);

class Root {
    [JsonPropertyName("event")]
    public List<Event> Events { get; set; }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading