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 complex JSON object fails to see collection

I’ve simplified the code (below) but I cannot figure out why the Result.Data property is not getting filled; it is always null. I’ve used jsonlint.com to validate the JSON (both this small sample and the full content). I built a separate project (using How to Deserialize a Complex JSON Object in C# .NET) and it successfully serializes the complex object listed there. But I cannot get this one to work and I’m stumped.

using System.Text.Json;

namespace JsonTest2;

public class Result
{
    public string? Total { get; set; }
    public string? Limit { get; set; }
    public string? Start { get; set; }
    protected List<Park>? Data { get; set; }
}

public class Park
{
    public string? Id { get; set; }
}

internal class Program
{
    var basepath = AppDomain.CurrentDomain.BaseDirectory;
    var filepath = basepath.Split("\\bin")[0];
    var filename = @$"{filepath}\NPS_response_small.json";
    var jsonstr = File.ReadAllText(filename);

    var response = JsonSerializer.Deserialize<Result>(jsonstr, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
}

This is the content of "NPS_response_small.json":

{
  "total": "468",
  "limit": "50",
  "start": "0",
  "data": [
    {
      "id": "77E0D7F0-1942-494A-ACE2-9004D2BDC59E"
    },
    {
      "id": "6DA17C86-088E-4B4D-B862-7C1BD5CF236B"
    },
    {
      "id": "E4C7784E-66A0-4D44-87D0-3E072F5FEF43"
    }
  ]
}

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

>Solution :

you have to chanbe a protected attribute of property Data to a public. Json deserializer doesnt have any acces to this property

public List<Park>? Data { 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