OK, just to burst your bubble: You cannot sort JArray. But if your JArray is just a list of numbers, or letters, you can convert the JArray into a list, sort that, and put it back into your JArray.
In my code I’m simulating this JSON array of strings:
["c", "e", "a", "d", "b"]
And I would like it to be sorted alphabetically. This is the code:
// Setting up my test data
JArray jArray = new JArray();
jArray.Add("c");
jArray.Add("e");
jArray.Add("a");
jArray.Add("d");
jArray.Add("b");
// This is the actual sorting
List<string> alphabet = jArray.ToObject<List<string>>();
alphabet.Sort();
jArray = JArray.FromObject(alphabet);
// Output the result
foreach (var item in jArray)
{
Console.WriteLine(item);
}
The JArray is first converted into a strongly typed list of strings. Then I can sort this list. Finally the sorted list can be put back into the JArray.
The output is:
a
b
c
d
e
That’s it. Happy coding.
MORE TO READ:
- Newtonsoft Json.Net
- C# Use HttpClient to GET JSON from API endpoint from briancaos
- C# Deserialize JSON to dynamic ExpandoObject() from briancaos
- C# Newtonsoft camelCasing the serialized JSON output from briancaos