Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Text.Json Deserialize Fails

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

I was getting an error about Unable to Parse without a parameterless constructor. I have since fixed that, but now my objects are de-serialized empty:

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

The jsonString contains 3 items with the correct data, and the deserialized list contains 3 items, but all the properties are empty.

enter image description here

like image 605
Origin Avatar asked Jul 05 '26 19:07

Origin


1 Answers

The new json library is case sensitive by default. You can change this by providing a settings option. Here is a sample:

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);
}
like image 134
Zsolt Bendes Avatar answered Jul 09 '26 14:07

Zsolt Bendes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!