使属性不区分大小写

Dan*_*med 2 .net c# utf8json

编辑:我使用的是Utf8Json而不是System.Text.Json

有没有可能的方法使 Utf8Json 反序列化器不区分大小写?目前,如果 json key-case 与 property-case 不匹配,则不会填充值。

我不想使用[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; }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*idG 6

您只需传入一个属性设置为 true 的JsonSerializerOptions对象即可PropertyNameCaseInsensitive。例如:

var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true
};

var obj = JsonSerializer.Deserialize<Temp>(json, options);
Run Code Online (Sandbox Code Playgroud)