Danial Ahmed
Danial Ahmed

Reputation: 866

Make properties case insensitive

EDIT: I am using Utf8Json not System.Text.Json

Is there any possible way to make Utf8Json Deserializer case insensitive? Currently if json key-case doesn't match property-case then values are not populated.

I don't want to use [DataMember(Name ="...")]

class Program
{
    static void Main(string[] args)
    {
        string json = "{\"testprop\":123,\"name\":\"TestObject\"}";
        var obj = JsonSerializer.Deserialize<Temp>(json);
        Console.ReadKey();
    }
}

public class Temp
{
    public int TestProp { get; set; }
    public string Name { get; set; }
}

Upvotes: 2

Views: 1346

Answers (1)

DavidG
DavidG

Reputation: 119017

You just need to pass in a JsonSerializerOptions object with the PropertyNameCaseInsensitive property set to true. For example:

var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true
};

var obj = JsonSerializer.Deserialize<Temp>(json, options);

Upvotes: 6

Related Questions