1

We have a class as shown below:

public class KeyVal<Key, Val>
{
    public Key Id { get; set; }
    public Val Text { get; set; }

    
    public KeyVal() { }

    public KeyVal(Key key, Val val)
    {
        this.Id = key;
        this.Text = val;
    }
}

We are sending a Json string from the client using javascript to our controller action as follows:

[{"id":7.4,"text":false},{"id":9.0,"text":true}]

which when looked at the controller as an argument it looks perfectly ok and identical to what was sent:

[{"id":7.4,"text":false},{"id":9.0,"text":true}]

We are trying to deserialize this into the calss above using the following code:

var deserialized= System.Text.Json.JsonSerializer.Deserialize<List<KeyVal<float?, bool>>>(list)

But ufortunately we keep getting nulls for the id and always false for the text property. i.e. its not being deserialized into an instance of our class.

Any ideas?

8
  • 1
    Try matching the case on member names. Commented Sep 13 at 21:20
  • 1
    Add the json properties name, and case-insensitive matching for the deserialize call, It will resolve the issue. public class KeyVal<Key, Val> { [JsonPropertyName("id")] public Key Id { get; set; } [JsonPropertyName("text")] public Val Text { get; set; } public KeyVal() {} public KeyVal(Key key, Val val) { Id = key; Text = val; } } Commented Sep 13 at 21:32
  • 1
    Set JsonSerializerOptions.PropertyNameCaseInsensitive = true, or set JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase, both as shown in JsonSerializer.Deserialize fails. Commented Sep 13 at 21:35
  • 1
    Or if you are using .NET 9 or later you can use JsonSerializerOptions.Web which sets both PropertyNameCaseInsensitive and CamelCase, see dotnetfiddle.net/Zdm7tW. So should we mark your question as a duplicate of the other question? Commented Sep 13 at 21:54
  • Yes. Sorry I did not see that thread. Commented Sep 13 at 22:14

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.