R
R
run1822019-07-28 18:01:16
JSON
run182, 2019-07-28 18:01:16

How to sort json objects in c#

How to sort this object as well as nested ones?

{
    "30": {
       "3":{},
       "0":{}
    },
    "11":{}
}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
R
run182, 2019-07-29
@run182

Found this solution:

public static void Main()
  {
    string json = @"{300:[{'Lygis':2,'Patiekalo_ID':30}],110:[{'Lygis':3,'Patiekalo_ID':31}]}";
    var jObj = (JObject)JsonConvert.DeserializeObject(json);
    Sort(jObj);
    string newJson = jObj.ToString();
    Console.WriteLine(newJson);
  }
  static void Sort(JObject jObj)
  {
    var props = jObj.Properties().ToList();
    foreach (var prop in props)
    {
      prop.Remove();
    }

    foreach (var prop in props.OrderBy(p=>Int32.Parse(p.Name)))
    {
      jObj.Add(prop);
      if(prop.Value is JObject)
        Sort((JObject)prop.Value);
    }
  }

Y
Yuri Esin, 2019-07-28
@Exomode

1. Parse all json in Dictionary using Newtonsoft.Json or other means;
2. Sort through Linq either by dictionary keys or by values.

F
freeExec, 2019-07-28
@freeExec

Json is text, it is not sortable.
Json needs to be converted to an object (data model). But even there you can only sort lists, but you don’t have lists.
See all sorts of SimpleJson, Newtonsoft and others.

D
Dmitry Bashinsky, 2019-07-29
@BashkaMen

var json = "{\r\n    \"30\": {\r\n       \"3\":{},\r\n       \"0\":{}\r\n    },\r\n    \"11\":{}\r\n}";
var dict = JsonConvert.DeserializeObject<Dictionary<int, Dictionary<int, object>>>(json);

var res = dict.OrderBy(s => s.Key).ToDictionary(s=> s.Key, s=> s.Value);

sorted by key

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question