要统计JSON中不同字段的数据,你可以使用C#中的Newtonsoft.Json库来解析JSON,并使用Dictionary或List来保存不同字段的数据。

下面是一个示例代码,演示如何统计JSON中不同字段的数据:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
}

public class Program
{
    public static void Main()
    {
        string json = @"[
            { 'Name': 'John', 'Age': 25, 'City': 'New York' },
            { 'Name': 'Jane', 'Age': 30, 'City': 'Los Angeles' },
            { 'Name': 'Bob', 'Age': 35, 'City': 'Chicago' },
            { 'Name': 'Alice', 'Age': 25, 'City': 'New York' }
        ]";

        List<Person> people = JsonConvert.DeserializeObject<List<Person>>(json);

        Dictionary<string, int> ageCounts = new Dictionary<string, int>();
        Dictionary<string, int> cityCounts = new Dictionary<string, int>();

        foreach (Person person in people)
        {
            // 统计年龄
            if (ageCounts.ContainsKey(person.Age.ToString()))
            {
                ageCounts[person.Age.ToString()]++;
            }
            else
            {
                ageCounts[person.Age.ToString()] = 1;
            }

            // 统计城市
            if (cityCounts.ContainsKey(person.City))
            {
                cityCounts[person.City]++;
            }
            else
            {
                cityCounts[person.City] = 1;
            }
        }

        Console.WriteLine("年龄统计结果:");
        foreach (KeyValuePair<string, int> ageCount in ageCounts)
        {
            Console.WriteLine("年龄 {0} 的人数:{1}", ageCount.Key, ageCount.Value);
        }

        Console.WriteLine();

        Console.WriteLine("城市统计结果:");
        foreach (KeyValuePair<string, int> cityCount in cityCounts)
        {
            Console.WriteLine("城市 {0} 的人数:{1}", cityCount.Key, cityCount.Value);
        }
    }
}

上述代码中,我们首先定义了一个Person类来表示JSON中的每个对象。然后使用JsonConvert.DeserializeObject<List<Person>>(json)将JSON字符串解析为List<Person>对象。

接下来,我们使用Dictionary<string, int>类型的ageCountscityCounts来统计不同年龄和城市的人数。在遍历people列表时,我们检查年龄和城市是否已经存在于字典中,如果已经存在则增加对应的计数,否则将新的年龄或城市添加到字典中并初始化计数为1。

最后,我们使用Console.WriteLine输出统计结果。

运行上述代码,你将得到类似以下的输出:

年龄统计结果:
年龄 25 的人数:2
年龄 30 的人数:1
年龄 35 的人数:1

城市统计结果:
城市 New York 的人数:2
城市 Los Angeles 的人数:1
城市 Chicago 的人数:1

这样,你就可以按照自己的需求统计JSON中不同字段的数据了

C#我有一个表里面存的json我怎么去统计里面的不同字段数据呢

原文地址: http://www.cveoy.top/t/topic/h7XY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录