1. 程式人生 > >用 GroupBy 把JSON物件分組

用 GroupBy 把JSON物件分組

不用寫實體類,將物件分組

 static void Main(string[] args)
        {

            var jsonStr = new StringBuilder();
            //準備JSON 模擬從資料庫查出的結果
            jsonStr.Append("[");
            jsonStr.Append("{\"clsid\":1,\"name\":\"wangdachui\",\"age\":23,\"email\":\"[email protected]\"},");
            jsonStr.Append("{\"clsid\":1,\"name\":\"wanglima\",\"age\":23,\"email\":\"
[email protected]
\"},"); jsonStr.Append("{\"clsid\":1,\"name\":\"chrome\",\"age\":23,\"email\":\"[email protected]\"},"); jsonStr.Append("{\"clsid\":1,\"name\":\"firefox\",\"age\":23,\"email\":\"[email protected]\"},"); jsonStr.Append("{\"clsid\":2,\"name\":\"lisi\",\"age\":50,\"email\":\"
[email protected]
\"},"); jsonStr.Append("{\"clsid\":2,\"name\":\"tianitan\",\"age\":50,\"email\":\"[email protected]\"},"); jsonStr.Append("{\"clsid\":2,\"name\":\"akali\",\"age\":50,\"email\":\"[email protected]\"},"); jsonStr.Append("{\"clsid\":2,\"name\":\"yi\",\"age\":50,\"email\":\"
[email protected]
\"},"); jsonStr.Append(" ]"); //定義反序列化結果的結構 var tempData = new[] { new { clsid =0, name=string.Empty, age=1, email=string.Empty } }; //反序列化 var objData = JsonConvert.DeserializeAnonymousType(jsonStr.ToString(), tempData); //分組 var groupData = objData.GroupBy(x => x.clsid).ToList(); Console.WriteLine(JsonConvert.SerializeObject(groupData)); Console.ReadLine(); }

效果:

結果JSON:

[

[{"clsid":1,"name":"wangdachui","age":23,"email":"[email protected]"},{"clsid":1,"name":"wanglima","age":23,"email":"[email protected]"},{"clsid":1,"name":"chrome","age":23,"email":"[email protected]"},{"clsid":1,"name":"firefox","age":23,"email":"[email protected]"}],

[{"clsid":2,"name":"lisi","age":50,"email":"[email protected]"},{"clsid":2,"name":"tianitan","age":50,"email":"[email protected]"},{"clsid":2,"name":"akali","age":50,"email":"[email protected]"},{"clsid":2,"name":"yi","age":50,"email":"[email protected]"}]

]