Search code examples
c#system.text.json

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 |

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; }
    }