【发布时间】: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