【问题标题】:System.Text.Json Deserialize FailsSystem.Text.Json 反序列化失败
【发布时间】:2020-05-27 22:21:11
【问题描述】:

有了这个 DTO:

public class QuestionDTO {
    public Guid Id { get; set; }
    public string Prompt { get; set; }
    public List<Answer> Choices { get; set; }

    public QuestionDTO() {

    }

    public QuestionDTO(Question question) {
        this.Id = question.Id;
        this.Prompt = question.Prompt;
        this.Choices = question.Choices;
    }
}

我收到一个关于 Unable to Parse without a parameterless constructor 的错误。我已经解决了这个问题,但现在我的对象被反序列化为空:

using System.Text.Json;
var results = JsonSerializer.Deserialize<List<QuestionDTO>>(jsonString);

jsonString 包含 3 项数据正确,反序列化列表包含 3 项,但所有属性均为空。

【问题讨论】:

标签: .net-core blazor system.text.json


【解决方案1】:

新的 json 库默认区分大小写。您可以通过提供设置选项来更改此设置。这是一个示例:

private JsonSerializerOptions _options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }

private async Task SampleRequest()
{
    var result = await HttpClient.GetStreamAsync(QueryHelpers.AddQueryString(queryString, queryParams));
    _expenses = await JsonSerializer.DeserializeAsync<List<Common.Dtos.Expenses.Models.Querys.ExpensesItem>>(result, _options);
}

【讨论】:

  • 默认的 .NET core API 将 JSON 序列化为驼峰式,默认的 System.Text.Json 期望 JSON 匹配类。因此,这两个来自 .NET 的默认值是冲突的,并导致它在没有上述特殊参数的情况下“开箱即用”失败。
猜你喜欢
  • 2021-07-17
  • 1970-01-01
  • 2020-02-20
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
相关资源
最近更新 更多