CodexBloom - Programming Q&A Platform

how to to Deserialize JSON to Custom Object with System.Text.Json in .NET 7

πŸ‘€ Views: 1 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-11
c# .net-7 json serialization C#

I've been banging my head against this for hours. I am running into an scenario trying to deserialize a JSON response into a custom class using `System.Text.Json` in .NET 7. The JSON response structure seems to be correct, but I keep getting a `JsonException` with the message: `The JSON value could not be converted to System.Collections.Generic.List`1[MyNamespace.MyClass].` Here’s the JSON I’m trying to deserialize: ```json { "items": [ { "id": 1, "name": "Item 1" }, { "id": 2, "name": "Item 2" } ] } ``` My target class structure looks like this: ```csharp public class MyClass { public int Id { get; set; } public string Name { get; set; } } public class MyResponse { public List<MyClass> Items { get; set; } } ``` When I attempt to deserialize with the following code: ```csharp var jsonString = await response.Content.ReadAsStringAsync(); var result = JsonSerializer.Deserialize<MyResponse>(jsonString); ``` I receive the aforementioned exception. I have verified that the JSON string is valid using online validators, and I’ve also tried adding `[JsonPropertyName]` attributes to the `MyClass` properties with no success. Has anyone encountered this scenario or have suggestions on how to resolve it? Any help would be greatly appreciated! Is this even possible?