unknown_boundaries
unknown_boundaries

Reputation: 1590

c# - Newtonsoft - Custom sort IEnumerable property - JSON

Consider the Node class. Using Newtonsoft to convert it into the JSON.

class Node {
   IList<Node> Nodes { get; }
}

I'm currently implementing default sorting logic as -

class Node : IComparable<Node> {
   IList<Node> Nodes { get; }

   public int CompareTo(Node node) {
      // some default sorting logic
   }
}

Newtonsoft, while serializing using it, and giving JSON with Nodes sorted in same logic.

string jsonString = JsonConvert.SerializeObject(
   deserializedObject, 
   Formatting.None, 
   new JsonSerializerSettings
   {
            // some settings
   });

Question: Now, I want to pass something like IComparer to JsonConvert.SerializeObject() method, so that JSON should have Nodes collection in a new sorting logic.

In some way I want to give freedom to caller to sort the collection in their way rather than default one, which would be used otherwise.

Don't know if there is a easy way of doing it? Any suggestions please?

Upvotes: 0

Views: 608

Answers (1)

Venu prasad H S
Venu prasad H S

Reputation: 241

There is no way to pass IComparer to JsonConvert.SerializeObject(). You can Sort the list of object using custom sort(IComparer) logic and pass the list to Serialization.

But, as you said, you can pass IComparer to Custom method and accomplish the task. as follows,

class Node
    {
        IList<Node> Nodes { get; set; }
        internal string Serialize(IComparer<Node> comparer)
        {
            Nodes = (IList<Node>)Nodes.OrderBy(c => c, comparer);
            return JsonConvert.SerializeObject(Nodes, Formatting.Indented, new JsonSerializerSettings() { });
        }
    }
    class SortHelper : IComparer<Node>
    {
        int IComparer<Node>.Compare(Node x, Node y)
        {
            // compare object x and y by custom logic
            return 0;
        }
    }

and call the following method with the above writter custom IComparer

string jsonString = node.Serialize(new SortHelper());

Upvotes: 2

Related Questions