Search code examples
c#asp.netblazorblazor-client-sidesystem.text.json

JsonSerializer.Deserialize not populating list within object


I'm working on a server-side Blazor application and am having trouble with a particular API call which is returning the below JSON.

{
  "id": 2,
  "status": 1,
  "fileName": "Test PDF",
  "fileType": "PDF",
  "fileBytes": "",
  "allSchemes": false,
  "dateModified": "2020-06-12T12:32:08.99",
  "dateCreated": "2020-06-11T11:32:19.877",
  "isNew": false,
  "schemes": [
    {
      "schemeCode": "0185",
      "schemeName": null,
      "baseCurrency": null
    },
    {
      "schemeCode": "0186",
      "schemeName": null,
      "baseCurrency": null
    }
  ]
}

However, when I deserialize using the below code the list of schemes is always 0. The other details are populated as expected

var accessToken = await _apiService.RequestNewToken(_httpClient);
_httpClient.SetBearerToken(accessToken);

return await JsonSerializer.DeserializeAsync<SchemeDocument>
    (await _httpClient.GetStreamAsync($"api/schemeDocument/{id}"), new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

The SchemeDocument class is

public class SchemeDocument
{        
    public int Id { get; set; }

    public SchemeDocumentStatus Status { get; set; }

    [Display(Name = "File Name")]
    public string FileName { get; set; }

    [Display(Name = "First Type")]
    public string FileType { get; set; }

    public byte[] FileBytes { get; set; }

    [Display(Name = "All Schemes")]
    public bool AllSchemes { get; set; }        

    public DateTime? DateModified { get; set; }

    public DateTime DateCreated { get; set; }

    [Computed]
    public bool IsNew => this.Id == default(int);

    [Write(false)]
    public List<Scheme> Schemes { get; } = new List<Scheme>();
}

Solution

  • Your List property needs a public setter.

    It's one of the reasons I still use Newtonsoft JSON, because it lets me have private setters.