Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

1 Answers

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; }
}
like image 90
Guru Stron Avatar answered Jun 16 '26 06:06

Guru Stron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!