jqgrid filter deserialization in ASP.NET 5 MVC application fails using System.Text.Json.JsonSerializer
To reproduce, run the code
var _filters ="{\"groupOp\":\"AND\",\"rules\":[{\"field\":\"Toode\",\"op\":\"cn\",\"data\":\"\"}]}";
var filtersList = JsonSerializer.Deserialize<Filter>(_filters, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
Result:
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 classes used in deserialization:
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
}
In .NET 4.6 it worked using
var serializer = new JavaScriptSerializer();
var filtersList = serializer.Deserialize<Filter>(_filters);
How to make it work in .NET 5 ?
In Net 5 you have to install Newtonsoft.Json using Nuget. This code allows to deserilize
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; }
}