【问题标题】:How to assign values to a class and create json如何为类赋值并创建json
【发布时间】:2020-03-11 01:00:18
【问题描述】:

我正在尝试为类分配值以构建 JSON 字符串。目标是生成如下所示的内容。

    {
    "ProductType" : "Spotlight_Comp",
        "SimulatedData" : [ 
            {
                "value" : 1819.00923045901,
                "units" : "hp",
                "tag" : "comp/totalIhp",
                "name" : "Compressor - Total IHP"
            }, 
            {
                "value" : 789.294125,
                "units" : "RPM",
                "tag" : "comp/averageSpeed",
                "name" : "Compressor - Speed"
            }, 
            {
                "value" : 2064.74658240481,
                "units" : "hp",
                "tag" : "comp/totalBhp",
                "name" : "Compressor - Total BHP"
            }
    ]
}

但我在找出正确的语法来为 SimulatedData 键创建对象数组时遇到问题。下面,是我的代码。我尝试了各种不同的语法,但未能找到解决方案。

public static void CreateJson(string productType, string units, string simTag, string name, string value)
        {
            Simulator.Root data = new Simulator.Root
            {
                ProductType = productType,
                SimulatedData =
                {

                }  
                //SimulatedData = new SimulatedData { value = value, units = units, tag = simTag, name = name }
            };

            string jsonOutput = JsonConvert.SerializeObject(data, Formatting.Indented);
            Console.WriteLine(jsonOutput);
        }

在下面构建 JSON 的类代码

      public class Root
        {
            public string ProductType { get; set; }
            public SimulatedData[] SimulatedData { get; set; }
        }

        public class SimulatedData
        {
            public string tag { get; set; }
            public string value { get; set; }
            public string units { get; set; }
            public string name { get; set; }
        }

    }
}

我确信我的课程结构方式让我感到厌烦。但这是我认为目前最好的方法。我有一种预感,问题在于有一个名为 SimulatedData 的类,然后在 Root 中有一个属性为 SimulatedData[]

【问题讨论】:

标签: c# arrays json serialization json.net


【解决方案1】:

如果你有一个对象,那么以下应该可以工作。

Simulator.Root data = new Simulator.Root
{
    ProductType = productType,
    SimulatedData = new []{new SimulatedData { value = value, units = units, tag = simTag, name = name }}
};    

对于多个对象只需创建一个列表或一个数组并将其分配给SimulatedData 属性:

var l = new List<SimulatedData>();

l.Add(...);
l.Add(...);
l.Add(...);

Simulator.Root data = new Simulator.Root
{
    ProductType = productType,
    SimulatedData = l.ToArray()
};    

您还可以更改 Root 以保留列表,而不是数组。

public List<SimulatedData> SimulatedData { get; set; }

【讨论】:

  • 这很好用!我将根据您的要求进行一些代码更改。我通过创建一个数组属性使自己感到困惑。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-15
  • 2021-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-29
  • 1970-01-01
相关资源
最近更新 更多