views:

59

answers:

1

I am getting a response back from a Google Search Appliance suggest service in the form of JSON in the following format

string jsonString = @"{ ""query"": ""t"", ""results"": [ { ""name"": ""tom"", ""type"": ""suggest"" }, { ""name"": ""tim"", ""type"": ""suggest"" }]}";

I want to sort the results list by name alphabeticaly and change the names to sentence case. I can do this in jquery but would prefer to do it on the server side for performance reasons.

I can sort the results but that returns an IEnumarable<Result> but I cant seem to sort the results within the object that is being serialised.

 string jsonString = @"{ ""query"": ""t"", ""results"": [ { ""name"": ""tom"", ""type"": ""suggest"" }, { ""name"": ""tim"", ""type"": ""suggest"" }]}";

JObject json = JObject.Parse(jsonString);

        var gsaSuggestions = JsonConvert.DeserializeObject<GSASuggestion>(jsonString);

        var orded = gsaSuggestions.ResultList.OrderBy<Result, string>(r => r.Name);

        string output = JsonConvert.SerializeObject(gsaSuggestions);
    }

    [JsonObject(MemberSerialization.OptOut)]
    public class GSASuggestion
    {
        [JsonProperty(PropertyName = "query")]
        public string Query {get; set;}
        [JsonProperty(PropertyName = "results")]
        public List<Result> ResultList {get; set;}
    }

    public class Result
    {
        [JsonProperty(PropertyName = "name")]
        public string Name {get; set;}
        [JsonProperty(PropertyName = "type")]
        public string Type {get; set;}
    }

the result should be:

{ "query": "t", "results": [ { "name": "Tim", "type": "suggest" }, { "name": "Tom", "type": "suggest" }]};
+7  A: 

You don't actually use the return value of OrderBy. Try:

gsaSuggestions.ResultList =
    gsaSuggestions.ResultList.OrderBy<Result, string>(r => r.Name).ToList();

Remember, OrderBy returns a new sequence with the results in order, and does not modify the original sequence. If you want gsaSuggestions.ResultList to be sorted then you will need to assign a sorted list to it.

You could also do an in-place sort using List.Sort:

gsaSuggestions.ResultList.Sort((x, y) => x.Name.CompareTo(y.Name));
Quartermeister