[英]how can i make formatted json file in c#
我想用C#制作格式化的json文件。
我想這樣:
{
"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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.