3 回答

TA貢獻1900條經(jīng)驗 獲得超5個贊
為此,您需要以這種方式構(gòu)造另一個匿名對象以獲取所需的json。
如果您對集合進行序列化,那么顯然它將轉(zhuǎn)換為json中的array:
var obj = new
{
Result = new
{
FirstSetting = new
{
FirstKEy = "Property vs Inspections", color = "#FF6384", fontStyle = "Arial", sidePadding = 10
},
AnotherSettings = new
{
text = "another text", color = "#FF6384", fontStyle = "Arial", sidePadding = 10
}
}
};
生成的json將是:
{
"Result":{
"FirstSetting":{
"FirstKey":"Property vs Inspections",
"color":"#FF6384",
"fontStyle":"Arial",
"sidePadding":10
},
"anotherSettings":{
"text":"another text",
"color":"#FF6384",
"fontStyle":"Arial",
"sidePadding":10
}
}
}

TA貢獻1811條經(jīng)驗 獲得超4個贊
并不是那樣會更好,但是如果有人發(fā)現(xiàn)它有用,那么您也可以為此使用字典。它仍然是干凈的代碼,并且從列表中刪除了第一個對象“ Result”。我有點覺得它更干凈,但這是首選。
var collection = new Dictionary<object, object>()
{
["FirstSetting"] = new
{
FirstKEy = "Property vs Inspections",
color = "#FF6384",
fontStyle = "Arial",
sidePadding = 10,
},
["AnotherSettings"] = new
{
text = "another text",
color = "#FF6384",
fontStyle = "Arial",
sidePadding = 10,
}
};
var jsonString = JsonConvert.SerializeObject(collection);
它輸出到:
{
"FirstSetting":
{
"FirstKEy":"Property vs Inspections",
"color":"#FF6384",
"fontStyle":"Arial",
"sidePadding":10
},
"AnotherSettings":
{
"text":"another text",
"color":"#FF6384",
"fontStyle":"Arial",
"sidePadding":10
}
}

TA貢獻1827條經(jīng)驗 獲得超9個贊
我認(rèn)為,將其放在一個對象中會使它更具可讀性。
Object mySettings = new {
? ? FirstSetting = new {
? ? ? ? ? ? FirstKEy = "Property vs Inspections",
? ? ? ? ? ? color = "#FF6384",
? ? ? ? ? ? fontStyle = "Arial",
? ? ? ? ? ? sidePadding = 10,
? ? },
? ? AnotherSettings = new {
? ? ? ? text = "another text",
? ? ? ? color = "#FF6384",
? ? ? ? fontStyle = "Arial",
? ? ? ? sidePadding = 10,
? ? }
};
以上可能會給您所需的結(jié)果。
- 3 回答
- 0 關(guān)注
- 311 瀏覽
添加回答
舉報