【问题标题】:JsonSerializer.Deserialize not populating list within object [duplicate]JsonSerializer.Deserialize 不填充对象内的列表 [重复]
【发布时间】:2020-06-12 14:20:29
【问题描述】:

我正在开发服务器端 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>();
}

【问题讨论】:

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


【解决方案1】:

您的 List 属性需要一个公共设置器。

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

【讨论】:

  • 非常感谢。我已经确认我现有的代码可以通过添加公共设置器或切换到 Newtonsoft JSON 来工作。
猜你喜欢
  • 2017-11-28
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多