Deserialize Json array in .NET7 project gives error

79 Views Asked by At

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

There are 2 best solutions below

0
On BEST ANSWER

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

you have list of events.

{
    "events": [
        {
            "year": 1945
        },
        {
            "year": 1945
        }
    ]
}


public partial class Events
{
    [JsonProperty("events")]
    public virtual List<Event> eventList { get; set; }
}

public partial class Event
{
    [JsonProperty("year")]
    public virtual long Year { get; set; }
}