Sorting a JSON Object using Linq

本小妞迷上赌 提交于 2019-12-24 05:09:05

问题


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" }]};

回答1:


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));


来源:https://stackoverflow.com/questions/3371122/sorting-a-json-object-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!