问题描述
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,JsonSerializerOptions options,T& value)
at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader,T& value)
at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader,ReadStack& state)
at System.Text.Json.JsonSerializer.ReadCore[TValue](JsonConverter jsonConverter,Utf8JsonReader& reader,ReadStack& state)
at System.Text.Json.JsonSerializer.ReadCore[TValue](Utf8JsonReader& reader,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; }
}