C# 如何在c中生成格式化的json文件#
我想用C#制作一个格式化的json文件 我想这样做:C# 如何在c中生成格式化的json文件#,c#,json,C#,Json,我想用C#制作一个格式化的json文件 我想这样做: { "LiftPositioner" : [ "LiftMax" : 5, "LiftMin" : 0 ], "Temperature" : [ "CH0_Temp" : 25, "CH1_Temp" : 25 ] } 但结果是 { "LiftMax": 5, "LiftMin": 0, "CH0_Temp": 25, "CH1_Te
{
"LiftPositioner" : [
"LiftMax" : 5,
"LiftMin" : 0
],
"Temperature" : [
"CH0_Temp" : 25,
"CH1_Temp" : 25
]
}
但结果是
{
"LiftMax": 5,
"LiftMin": 0,
"CH0_Temp": 25,
"CH1_Temp": 25
}
这是我的代码:
var json = new JObject();
json.Add("LiftMax", Convert.ToInt32(radTextBox_LiftMax.Text));
json.Add("LiftMin", Convert.ToInt32(radTextBox_LiftMin.Text));
json.Add("CH0_Temp", Convert.ToInt32(radTextBox_CH0.Text));
json.Add("CH1_Temp", Convert.ToInt32(radTextBox_CH1.Text));
string strJson = JsonConvert.SerializeObject(json, Formatting.Indented);
File.WriteAllText(@"ValueSetting.json", strJson);
我必须在代码中更改什么?如果要运行
JsonConvert.SerializeObject
,只需使用您的值创建一个匿名类型,就可以更轻松地进行更改。以下内容将为您提供所需的结果:
var item = new
{
LiftPositioner = new[]
{
new
{
LiftMax = 5,
LiftMin = 0
}
},
Temperature = new[]
{
new
{
CH0_Temp = 25,
CH1_Temp = 25
}
}
};
string strJson = JsonConvert.SerializeObject(item, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(strJson);
其输出如下:
{
"LiftPositioner": [
{
"LiftMax": 5,
"LiftMin": 0
}
],
"Temperature": [
{
"CH0_Temp": 25,
"CH1_Temp": 25
}
]
}
如果您不需要LiftPositioner
和Temperature
属性的列表,可以将其减少为:
var item = new
{
LiftPositioner =
new
{
LiftMax = 5,
LiftMin = 0
},
Temperature =
new
{
CH0_Temp = 25,
CH1_Temp = 25
}
};
这将产生
{
"LiftPositioner": {
"LiftMax": 5,
"LiftMin": 0
},
"Temperature": {
"CH0_Temp": 25,
"CH1_Temp": 25
}
}
是否应列出
LiftPositioner
和Temperature
的值?