C# 统计 JSON 中不同字段数据的方法
{"title":"C# 统计 JSON 中不同字段数据的方法","description":"本文介绍如何使用 C# 中的 Newtonsoft.Json 库解析 JSON 数据,并使用 Dictionary 或 List 统计不同字段数据,例如年龄、城市等。","keywords":"C#, JSON, 解析, 统计, 字段, 数据, Dictionary, List, Newtonsoft.Json","content":"要统计 JSON 中不同字段的数据,你可以使用 C# 中的 Newtonsoft.Json 库来解析 JSON,并使用 Dictionary 或 List 来保存不同字段的数据。\n\n下面是一个示例代码,演示如何统计 JSON 中不同字段的数据:\n\ncsharp\nusing Newtonsoft.Json;\nusing System;\nusing System.Collections.Generic;\n\npublic class Person\n{\n public string Name { get; set; }\n public int Age { get; set; }\n public string City { get; set; }\n}\n\npublic class Program\n{\n public static void Main()\n {\n string json = "[\n { 'Name': 'John', 'Age': 25, 'City': 'New York' },\n { 'Name': 'Jane', 'Age': 30, 'City': 'Los Angeles' },\n { 'Name': 'Bob', 'Age': 35, 'City': 'Chicago' },\n { 'Name': 'Alice', 'Age': 25, 'City': 'New York' }\n ]";\n\n List<Person> people = JsonConvert.DeserializeObject<List<Person>>(json);\n\n Dictionary<string, int> ageCounts = new Dictionary<string, int>();\n Dictionary<string, int> cityCounts = new Dictionary<string, int>();\n\n foreach (Person person in people)\n {\n // 统计年龄\n if (ageCounts.ContainsKey(person.Age.ToString()))\n {\n ageCounts[person.Age.ToString()]++;\n }\n else\n {\n ageCounts[person.Age.ToString()] = 1;\n }\n\n // 统计城市\n if (cityCounts.ContainsKey(person.City))\n {\n cityCounts[person.City]++;\n }\n else\n {\n cityCounts[person.City] = 1;\n }\n }\n\n Console.WriteLine("年龄统计结果:");\n foreach (KeyValuePair<string, int> ageCount in ageCounts)\n {\n Console.WriteLine("年龄 {0} 的人数:{1}", ageCount.Key, ageCount.Value);\n }\n\n Console.WriteLine();\n\n Console.WriteLine("城市统计结果:");\n foreach (KeyValuePair<string, int> cityCount in cityCounts)\n {\n Console.WriteLine("城市 {0} 的人数:{1}", cityCount.Key, cityCount.Value);\n }\n }\n}\n\n\n上述代码中,我们首先定义了一个Person类来表示 JSON 中的每个对象。然后使用JsonConvert.DeserializeObject<List<Person>>(json)将 JSON 字符串解析为List<Person>对象。\n\n接下来,我们使用Dictionary<string, int>类型的ageCounts和cityCounts来统计不同年龄和城市的人数。在遍历people列表时,我们检查年龄和城市是否已经存在于字典中,如果已经存在则增加对应的计数,否则将新的年龄或城市添加到字典中并初始化计数为1。\n\n最后,我们使用Console.WriteLine输出统计结果。\n\n运行上述代码,你将得到类似以下的输出:\n\n\n年龄统计结果:\n年龄 25 的人数:2\n年龄 30 的人数:1\n年龄 35 的人数:1\n\n城市统计结果:\n城市 New York 的人数:2\n城市 Los Angeles 的人数:1\n城市 Chicago 的人数:1\n\n\n这样,你就可以按照自己的需求统计 JSON 中不同字段的数据了。
原文地址: https://www.cveoy.top/t/topic/pQNz 著作权归作者所有。请勿转载和采集!