3

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

dbc
  • 104,963
  • 20
  • 228
  • 340
Origin
  • 1,943
  • 13
  • 33
  • 1
    Is your JSON camelCase or PascalCase ? – agua from mars May 28 '20 at 06:48
  • 1
    Can you attach the json that you try to deserialize? – Stelios Giakoumidis May 28 '20 at 07:17
  • Both of these comments are spot on - it's a casing issue. I guess it is "well documented" that MVC in .NET will default to camel Casing – Origin May 28 '20 at 20:46
  • Does this answer your question? [System.Text.JSON doesn't deserialize what Newtonsoft does](https://stackoverflow.com/questions/58879190/system-text-json-doesnt-deserialize-what-newtonsoft-does) – dbc Jun 11 '20 at 20:47
  • And/or: [ASP.NET Core 3.0 System.Text.Json Camel Case Serialization](https://stackoverflow.com/q/58476681/3744182). – dbc Jun 11 '20 at 20:48

1 Answers1

6

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);
}
Zsolt Bendes
  • 2,219
  • 12
  • 18
  • 3
    The default .NET core API serializes JSON as camel case, and the default System.Text.Json expects the JSON to match the classes. So these two defaults, both from .NET, are conflicting and cause it to fail "out of the box" without the special parameter mentioned above. – Origin May 28 '20 at 21:53
  • 1
    What a boneheaded default! I can't believe there aren't more results for "why are all my properties null". No wonder people use Newtonsoft... – Coxy Dec 15 '22 at 07:32