c# - JsonSerializer.Deserialize 不填充对象内的列表

标签 c# asp.net blazor blazor-client-side system.text.json

<分区>

我正在开发服务器端 Blazor 应用程序,但在处理返回以下 JSON 的特定 API 调用时遇到了问题。

{
  "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
    }
  ]
}

但是,当我使用以下代码反序列化时,方案列表始终为 0。其他详细信息按预期填充

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

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

SchemeDocument 类是

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

最佳答案

您的 List 属性需要一个公共(public) setter 。

这是我仍然使用 Newtonsoft JSON 的原因之一,因为它让我拥有私有(private) setter。

关于c# - JsonSerializer.Deserialize 不填充对象内的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62346229/

相关文章:

c# - 以通用表达式和 Action 作为参数调用方法

c# - 如何在 Linq 查询中的 where 条件下使用数组

asp.net - 在ASP.NET Web应用程序内部托管Powershell

c# - 如何在 Blazor 中的输入更改上绑定(bind)和运行异步方法

blazor - 服务器端 Blazor 的 WYSIWYG HTML 编辑器

blazor - 使用特定格式绑定(bind) Blazor 中的值

C# 缺少 MSVCR100.dll

c# - ICommand CanExecute 被调用,即使在 ViewModel 从 UI 中移除之后

javascript - JQuery 数据表上的编辑按钮

c# - 设置中继器中项目的 ID