如何在 .NET 5 中反序列化枚举和数组

How to deserialize enum and array in .NET 5

ASP.NET 5 MVC 应用程序中的 jqgrid 过滤器反序列化使用 System.Text.Json.JsonSerializer

失败

要重现,运行 代码

var _filters ="{\"groupOp\":\"AND\",\"rules\":[{\"field\":\"Toode\",\"op\":\"cn\",\"data\":\"\"}]}";

var filtersList = JsonSerializer.Deserialize<Filter>(_filters, new JsonSerializerOptions
                { 
                    PropertyNameCaseInsensitive = true
                });

结果:

The JSON value could not be converted to MyApp.Controllers.GroupOp. Path: $.groupOp | LineNumber: 0 | BytePositionInLine: 16.


System.Text.Json.JsonException: The JSON value could not be converted to MyApp.Controllers.GroupOp. Path: $.groupOp | LineNumber: 0 | BytePositionInLine: 16.
   at System.Text.Json.ThrowHelper.ThrowJsonException(String message)
   at System.Text.Json.Serialization.Converters.EnumConverter`1.Read(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options)
   at System.Text.Json.JsonPropertyInfo`1.ReadJsonAndSetMember(Object obj, ReadStack& state, Utf8JsonReader& reader)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadCore[TValue](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadCore[TValue](Utf8JsonReader& reader, Type returnType, JsonSerializerOptions options)
   at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, Type returnType, JsonSerializerOptions options)
   at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)

反序列化中使用的jqgrid 类:

public class Filter
{
    public GroupOp GroupOp { get; set; }
    public List<Rule> Rules { get; set; }
    public List<Filter> Groups { get; set; }
}

public enum GroupOp
{
    AND,
    OR
}

public class Rule
{
    public string Field { get; set; }
    public Operations Op { get; set; }
    public string Data { get; set; }
}

public enum Operations
{
    eq,
    ne,
    cn,
    le
}

在 .NET 4.6 中它可以使用

var serializer = new JavaScriptSerializer();
var filtersList = serializer.Deserialize<Filter>(_filters);

如何让它在 .NET 5 中工作?

在 Net 5 中,您必须使用 Nuget 安装 Newtonsoft.Json。此代码允许反序列化

var _filters = "{\"groupOp\":\"AND\",\"rules\":[{\"field\":\"Toode\",\"op\":\"cn\",\"data\":\"\"}]}";
    var filtersList = JsonConvert.DeserializeObject<Filter>(_filters);
    
}


public class Filter
{
    public GroupOp groupOp { get; set; }
    public List<Rule> rules { get; set; }
    
}