json.net to System.text.json desiration for nested class in .net 5

Viewed 255

I am having issue.I have migrated Json.net to system.text.json. Json serialization and deserialization of non nested simple class types are working fine..

Json Request:

{"args":{"pageIndex":1,"pageSize":10,"filteringOptions":[],"sortingOptions":[{"field":"ain","direction":"ASC"}]}}

For the below serialization of complex types are getting error..

 services.AddControllers()
            .AddJsonOptions(options =>
              {
                  options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());  // Input/Output date format
              });

Class:

 public class SearchPageRequest
{
    public PageSearchArgs Args { get; set; } = new PageSearchArgs();
}
 public class PageSearchArgs
    {            
       public int PageIndex { get; set; }
       public int PageSize { get; set; }
       public PagingStrategy PagingStrategy { get; set; }
       public List<SortingOption>? SortingOptions { get; set; }   //Only List are not mapping 
       public List<FilteringOption>? FilteringOptions { get; set; }
    }


 public class SortingOption
    {
     
        public string Field { get; set; } = null!;
        //[JsonPropertyName("direction")]     tested put Json property for all propertie
        public SortingDirection Direction { get; set; }
        public int Priority { get; set; }

        public enum SortingDirection
        {
            ASC,
            DESC
        }
    }

i am using default case in C# Class ( Pascal case) and in angular interface ( Camelcase).. in .net 5 and angular 10 application.

Error In model validation.

Key: "$.args.sortingOptions[0].direction" (Camelcase)

Value:The JSON value could not be converted to Application.Wrappers.Paging.SortingOption+SortingDirection. Path: $.args.sortingOptions[0].direction | LineNumber: 0 | BytePositionInLine: 109.

enter image description here

Please let me know..i am trying from 2 days..The data coming from angular slickdrid..if any changes i have to modify in c# class itlsef

What i have tried: (It is working fine in json.net)

  1. Json property name i have defined as camelcase

Based on error $.args.sortingOptions[0].direction is not mapping to SortingOptions of direction.which is enum property..Please let me know alternate solution?

1 Answers

Do you really need to migrate Json.net to system.text.json?

According to https://visualstudiomagazine.com/articles/2020/07/28/json-serializers.aspx

If you're already using Newtonsoft.Json in an existing project, you likely don't need to switch. If you absolutely need high JSON serialization/deserialization performance, go with System.Text.

Json.net has a few convenient features, that are not available in System.Text. It is better to use the package that is more suitable for the job.

Related