2

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; }
}
Danial Ahmed
  • 856
  • 1
  • 10
  • 26

1 Answers1

6

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);
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • isn't JsonSerializerOptions for System.Text.Json? If I use this then I will have to use the Deserializer from System.Text.Json instead of Utf8Json. – Danial Ahmed Jul 20 '22 at 09:08
  • As sorry, I missed that. So as far as I can tell there isn't an easy way to do it with Utf8Json. You might be able to make your own formatted `IJsonFormatter` if you copy how the internal ones work. There's one in there for camel case that you could copy, but it would require a tonne of copying out internal code that hasn't been exposed as public for some reason. Is there a reason you don't want to use System.Text.Json? Utf8Json hasn't really been changed for 2 years now so I don't think there's many reasons to stick with it. – DavidG Jul 20 '22 at 11:57
  • Project requirement, and Utf8Json is 4x faster compared to System.Text.Json – Danial Ahmed Jul 21 '22 at 05:44
  • It used to be 4x faster but that isn't the case any more. Especially since STJ added source generators. It wouldn't surprise me if STJ is actually faster now. – DavidG Jul 21 '22 at 08:53