How to Sort a JsonArray

4.6k Views Asked by At

We're using System.JSON to consume an api call and there doesn't seem to be a way to sort the data.

Running in C# ASP.NET 4 and ASP.NET MVC 3.

Here is an example of out data call:

string requestURL = /*URL to the API*/;
    WebRequest request = HttpWebRequest.Create(requestURL);
    using (var response = request.GetResponse()) {
        return JsonObject.Load(response.GetResponseStream());
    }

This function returns a JsonValue which is holding a JsonArray, which is what I'm trying to sort.

1

There are 1 best solutions below

4
Darin Dimitrov On

You haven't shown how your JSON look like nor by which property you want to order. Let's suppose that you have the following JSON:

[
    {
        "Id": 1,
        "Text": "item 1"
    },
    {
        "Id": 2,
        "Text": "item 2"
    },
    {
        "Id": 3,
        "Text": "item 3"
    },
    {
        "Id": 4,
        "Text": "item 4"
    },
    {
        "Id": 5,
        "Text": "item 5"
    }
]

and you want to order by the Id property in a descending order. This could be done for example like this:

class Program
{
    static void Main(string[] args)
    {
        string requestURL = "/URL to the API/";
        WebRequest request = HttpWebRequest.Create(requestURL);
        using (var response = request.GetResponse()) 
        {
            var result = JsonArray.Load(response.GetResponseStream());
            var orderedResult = result.OrderByDescending(x => x.Value["Id"].ReadAs<int>());
            foreach (var item in orderedResult)
            {
                Console.WriteLine("{0} : {1}", item.Value["Id"], item.Value["Text"]);
            }
        }
    }
}