1

I would like to sort the serialized properties with System.Text.Json. Actually, I want to put one property (ID) in the first place.

Follow my console application.

class Program
{
    static void Main(string[] args)
    {            
        Student student = new Student()
        {                
            Name = "Robert",
            Id = Guid.NewGuid(),
            LastName = "Alv",
            Check = "Ok"
        };

        var resultJson =  System.Text.Json.JsonSerializer.Serialize(student);
        Console.WriteLine(resultJson);
        Console.ReadLine();
        
    }
    class BaseClass1
    {            
        public Guid Id { get; set; }
    }

    class BaseClass2 : BaseClass1
    {
        
    }

    class People : BaseClass2
    {            
        public string Name { get; set; }
        public string LastName { get; set; }
        public string Check { get; set; }
    }

    class Student : BaseClass2
    {            
        public string Name { get; set; }
        public string LastName { get; set; }
        public string Check { get; set; }
    }       
}

  

The result of the program above is {"Name":"Robert","LastName":"Alv","Check":"Ok","Id":"4bd17c0c-f610-414d-8f6c-49ca8957ef3f"}

But I want the result below

{"Id":"4bd17c0c-f610-414d-8f6c-49ca8957ef3f","Name":"Robert","LastName":"Alv","Check":"Ok"}

dbc
  • 104,963
  • 20
  • 228
  • 340
  • Properties don't really have order... neither in C# nor in JSON. (indeed there is [structlayoutattribute](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.structlayoutattribute?view=net-5.0) but it does not really apply to text serialization). Some [edit] to clarify what is exactly is your goal and what actual problem you hope to solve with this approach would be welcome. – Alexei Levenkov Aug 31 '21 at 21:40
  • Hello @AlexeiLevenkov! Actually I need it to my Rest Api. I would like to return the property "ID" in the first place in the Json result. But I need the base class with "ID" for many reasons in my app. – Rogerio Potenza Aug 31 '21 at 21:43
  • If you would be interested in just what you claim you are you'd likely already found duplicate https://stackoverflow.com/questions/3330989/order-of-serialized-fields-using-json-net... but you need automapper answer based on the title/tags - so now with clear goal someone could possibly come up with and answer to that (also I'm pretty sure it is not possible as automapper does not know about JSON serialization) – Alexei Levenkov Aug 31 '21 at 21:52
  • Thanks @AlexeiLevenkov! According to my question, if I remove the inheritance, the properties order work correctly. I have aleady checked the thread and it did not solve my problem. – Rogerio Potenza Aug 31 '21 at 21:58
  • You should [edit] it into the question along with real [MCVE]. I.e. currently the question claims some relation to automapper but there is no traces of using result of mapping in the code. Nor any definition of `People` type... – Alexei Levenkov Aug 31 '21 at 22:04
  • You are right! I was using System.Text.Json. After changed to NewtonSoft.Json it worked! Can I answer my question? – Rogerio Potenza Aug 31 '21 at 22:08
  • Duplicate: [.NET core 3: Order of serialization for JsonPropertyName (System.Text.Json.Serialization)](https://stackoverflow.com/q/59134564/3744182) – dbc Sep 02 '21 at 19:18

2 Answers2

1

After reading the thread stackoverflow.com/questions/3330989 indicated by @AlexeiLevenkov. I realized that It is easier using NewtonSoft.Json. So I set the attribute [JsonProperty(Order = -2)] to "ID" property and exchange System.Text.Json.JsonSerializer.Serialize(student) for JsonConvert.SerializeObject(student); It worked properly!

Below is the code updated.

class Program
{
    static void Main(string[] args)
    {            
        Student student = new Student()
        {                
            Name = "Robert",
            Id = Guid.NewGuid(),
            LastName = "Alv",
            Check = "Ok"
        };

        var resultJson =  JsonConvert.SerializeObject(student);
        Console.WriteLine(resultJson);
        Console.ReadLine();
        
    }
    class BaseClass1
    {
        [JsonProperty(Order = -2)]
        public Guid Id { get; set; }
    }

    class BaseClass2 : BaseClass1
    {
        
    }

    class People : BaseClass2
    {            
        public string Name { get; set; }
        public string LastName { get; set; }
        public string Check { get; set; }
    }

    class Student : BaseClass2
    {            
        public string Name { get; set; }
        public string LastName { get; set; }
        public string Check { get; set; }
    }       
}
1

Not possible with System.Text.Json (yet). Supposedly in the works for a release "someday".

As you've found, it is possible with Newtonsoft.Json.

jspinella
  • 2,013
  • 3
  • 25
  • 39
  • I'm a bit confused; according to [this](https://github.com/dotnet/runtime/issues/728#issuecomment-881541832), the `JsonPropertyOrderAttribute` is available, and indeed I can decorate my POCO's properties with it (and it compiles), but it doesn't affect the ordering when returning said POCO from a web api action . Is it supposed to work with .NET 6? – BCA Nov 22 '21 at 22:32
  • IIRC I could also decorate properties with `JsonPropertyOrderAttribute` but it doesn't actually do anything. If you look at the last comment in that GitHub link, he's saying the attribute doesn't have write access to be able to modify order of the object. The same guy merges a relevant PR [here](https://github.com/dotnet/runtime/pull/55662) but I think that's just one of many obstacles blocking the actual sort override code that is still yet to come. I think. That would explain why it's still not working on .NET 6. – jspinella Nov 23 '21 at 18:54
  • That makes sense; thanks for the insights – BCA Nov 24 '21 at 12:40