开发者

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 use开发者_运维问答d 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"
    }
  ]
}


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

it would be much easier to use Newtonsoft.Json, but if you need protected for some reason, you can try this ( but I am not sure that it is a full replacement)

    public List<Park>? Data { protected get; init ; }
    
    [System.Text.Json.Serialization.JsonConstructor]
    public Result (List<Park>? Data, string? Total, string? Limit, string? Start)
    {
        this.Data=Data;
        this.Total=Total;
        this.Limit=Limit;
        this.Start=Start;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜