【问题标题】:Grouping values in a list and convert the output into JSON using C#将列表中的值分组并使用 C# 将输出转换为 JSON
【发布时间】:2016-02-26 03:58:03
【问题描述】:

我有一个对象列表。其中有4个属性。 Month, Category, 2015 & 2014

 Month  Category    2015    2014
    Jan A   10  100
    Jan B   20  200
    Jan C   30  300
    Jan D   40  400
    Feb B   50  500
    Feb C   60  600
    Feb D   70  700
    Mar A   80  800
    Mar I   90  900
    Mar J   100 1000

我想使用月份对值进行分组,并且我想生成这样的 JSON 输出。我通过在类别名称前面加上 curpre 关键字来在 JSON 对象中创建属性,它们代表的值来自 2014 and 2015

[{  
    name: "jan",
    curA: 10,
    preA: 100,
    curB: 20,
    preB: 200,
    curC: 30,
    preC: 400,
    curD: 40,
    preD: 400
}, {    
    name: "feb",
    curB: 50,
    preB: 500,
    curC: 60,
    preC: 600,
    curD: 70,
    preD: 700
}, {    
    name: "mat",
    curA: 80,
    preA: 800,
    curI: 90,
    preI: 900,
    curJ: 100,
    preJ: 1000
}]  

我可以使用 JSON.NET 将 C# 对象序列化为 JSON,但我正在努力创建一个可以转换为所需格式的类。

【问题讨论】:

    标签: c# json linq c#-4.0 c#-3.0


    【解决方案1】:

    您可以使用字典数组。

    var list = new List<Dictionary<string, int>> ();
    

    您必须弄清楚您希望如何根据数据来填充您的字典,但您需要在您希望的任意月/分段点内执行此操作:

    var data = new Dictionary<string, int>
    {
         { "name", 10 },
         { "curA", 100 },
         { "preA", 20 } // And so on...
    };
    list.Add(data);
    

    然后您可以以类似的方式将您的列表转换为 json:

    string json = JsonConvert.SerializeObject(points, Formatting.Indented);
    

    希望这会有所帮助!

    编辑:最初的问题是寻求帮助,将他的源列表转换为 JSON 字符串中所需的列表。

    在不知道源列表(对象、数据行等)的格式的情况下,我假设您只有一个对象列表。我的对象如下所示:

    public class ListRow {
        public string Month { get; set; }
        public string Category { get; set; }
        public string _2015 { get; set; }
        public string _2014 { get; set; }
    }
    

    我还假设您有一个名为 list 的变量,其中包含这些对象的列表。未填充的定义如下所示:

    var list = new List<ListRow> ();
    

    我很快将这段未经测试的代码放在一起,作为如何将源列表转换为新格式的指南。

        var convertedList = new List<Dictionary<string, string>> ();
        var groupedList = list.GroupBy (_ => _.Month);
        foreach (var item in groupedList) {
            var data = new Dictionary<string, string> ();
            data.Add ("name", item.Key);
            foreach (var value in item) {
                data.Add (string.Format ("cur{0}", value.Category), value._2015);
                data.Add (string.Format ("pre{0}", value.Category), value._2014);
            }
            convertedList.Add (data);
        }
    

    然后您需要序列化convertedList 变量。

    希望这能让您更接近您的解决方案。

    【讨论】:

    • 感谢您的回复,但我不知道随着价值的增长,这将如何扩展。这看起来更像是手动读取所有值并获得所需的结果。如果我错了,请纠正我
    • 不,我特别写道,您必须弄清楚如何根据数据填充字典。我给了你一个例子,它会给你你想要的 json……但我不熟悉你的数据或者你如何将它从列表转换为所需的属性。
    • 您的问题是要举例说明如何以正确的 json 输出数据,还是需要帮助弄清楚如何进行数据转换?我回答的是前者。
    • 在我的问题中,我已经指定了我拥有的数据,其可用格式(对象列表,每个对象用于 4 个属性)。我想将值转换为 json,我还想通过添加一些预定义的文本并使用现有属性来创建新属性。我需要确保随着对象数量的增加,相同的代码能够生成所需的输出,
    • 明白了,这更清楚一点。给我几分钟时间写点东西。
    【解决方案2】:

    这是我的实现:

        using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Dynamic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication3
    {
    
        public class Transactions
        {
            public string Month { get; set; }
            public string Cath { get; set; }
            public string Year { get; set; }
            public int Unit { get; set; }
        }
        class Program
        {
            static void Main(string[] args)
            {
                var transactionsList = new List<Transactions>();
                transactionsList.Add(new Transactions() { Month = "Jan", Cath = "A", Year = "pre", Unit = 10 });
                transactionsList.Add(new Transactions() { Month = "Jan", Cath = "A", Year = "cur", Unit = 100 });
                transactionsList.Add(new Transactions() { Month = "Jan", Cath = "B", Year = "pre", Unit = 20 });
                transactionsList.Add(new Transactions() { Month = "Jan", Cath = "B", Year = "cur", Unit = 200 });
                transactionsList.Add(new Transactions() { Month = "Jan", Cath = "C", Year = "pre", Unit = 30 });
                transactionsList.Add(new Transactions() { Month = "Jan", Cath = "C", Year = "cur", Unit = 300 });
                transactionsList.Add(new Transactions() { Month = "Jan", Cath = "D", Year = "pre", Unit = 40 });
                transactionsList.Add(new Transactions() { Month = "Jan", Cath = "D", Year = "cur", Unit = 400 });
                transactionsList.Add(new Transactions() { Month = "Feb", Cath = "B", Year = "pre", Unit = 50 });
                transactionsList.Add(new Transactions() { Month = "Feb", Cath = "B", Year = "cur", Unit = 500 });
    
    
                var transactionsQuery =
                    (from t in transactionsList
                    group t by t.Month into newGroup
                    orderby newGroup.Key descending
                    select newGroup).ToList();
    
    
                var dictionaryList = new List<Dictionary<string, object>>();
    
                foreach (var nameGroup in transactionsQuery)
                {
                    var data = new Dictionary<string, object>();
                    data.Add("name", nameGroup.Key);
    
                    foreach (var item in nameGroup)
                    {                   
                        data.Add(string.Format("{0}{1}", item.Year, item.Cath), item.Unit);
                    }
                    dictionaryList.Add(data);
    
                }
    
               var ser = JsonConvert.SerializeObject(dictionaryList);
    
                Console.WriteLine(ser);
                Console.ReadLine();
    
            }
        }
    }
    

    【讨论】:

    • 如果我的班级看起来像这样Year, Category, Month, Value,是否可以获得相同的输出。数据示例`2014 A Jan 100` & 2015 A Jan 10 。我说的是今年和上一年没有两列,我只有一列称为年份,年份将添加为行。如果数据格式发生变化,如何获得相同的输出?
    • 而不是 transactionsList.Add(new Transactions() { Month = "Jan", Cath = "A", Year = "pre", Unit = 10 }); put transactionsList.Add(new Transactions() { Year = "2014", Cath = "A", Month = "Jan", Unit = 100 });只需将您的 2014 替换为“pre”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 2021-01-01
    • 1970-01-01
    • 2015-08-26
    • 2019-04-30
    • 2022-08-17
    • 2013-08-22
    相关资源
    最近更新 更多