Morpheus
Morpheus

Reputation: 3523

Deserialize and sort

I have the following json format file, rankingOutput

{
    "12345": {
        "ABC": {
            "rank": 3, 
            "Comments": [
                "Good"
            ]
        }, 
        "DEF": {
            "rank": 2, 
            "Comments": [
                "Good"
            ]
        }, 
        "GHI": {
            "rank": 1, 
            "Comments": [
                "Bad"
            ]
        }
    }
}

I ma having the following deserialize code

JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, RankingsClass>>>(
                                               System.IO.File.ReadAllText(rankingOutput));

    public class RankingsClass
    {
        public int rank;
        public string[] comments;
    }    

Though the above code deserializes it properly, I am wondering if there is an option so that my deserializer will return the strings "ABC", "DEF" and "GHI" ranked in ascending order according to the rank field.

Upvotes: 1

Views: 1243

Answers (2)

Servy
Servy

Reputation: 203817

Dictionary is an unordered collection. There is no way for you to have any expectation of any order at all for the items in it. You'll need to use an entirely different data structure that is actually ordered, such as a SortedDictionary.

Upvotes: 0

Carsten Cors
Carsten Cors

Reputation: 2595

Try to use Linq on the result set like:

List<RankingsClass> list = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, RankingsClass>>>(System.IO.File.ReadAllText(rankingOutput));

return list.OrderByDescending(c => c.rank);

Upvotes: 0

Related Questions