2

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.

Brad Wilkie
  • 331
  • 4
  • 12

1 Answers1

2

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"]);
            }
        }
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • This answered one of the questions I had here (the Linq function), but I can't get anywhere with this because it seems like the System.Json classes don't implement iComparable, and therefor can't do any ordering. – Brad Wilkie Jul 27 '12 at 14:40
  • @BradWilkie, the `orderedResult` variable I have constructed in my example contains the ordered data. That's what I though you needed to do in the first place: get a strong typed ordered array from a JSON string that you consumed from a web service. Please correct me if I am wrong or misunderstood your requirement somehow. – Darin Dimitrov Jul 27 '12 at 14:54
  • No, you're exactly right in what I'm trying to do, but the JsonArray type does not seem to support the order methods. I keep getting errors wherever I try to do the sort. – Brad Wilkie Jul 27 '12 at 14:58
  • You cannot sort the JsonArray inline. You don't need to do that. Simply construct a new sorted array using LINQ. – Darin Dimitrov Jul 27 '12 at 14:59