使用值(C#)初始化字典
我有一个带有字典的模型,我想用默认值初始化它 下面是我现在的做法使用值(C#)初始化字典,c#,.net,dictionary,C#,.net,Dictionary,我有一个带有字典的模型,我想用默认值初始化它 下面是我现在的做法 public Dictionary<string, string> controllableProperties = new Dictionary<string, string> { {"controllableProperties", [{"name": "Reboot","type": {"@class": "com.avispl.symphony.api.dal.dto.cont
public Dictionary<string, string> controllableProperties = new Dictionary<string, string> {
{"controllableProperties", [{"name": "Reboot","type": {"@class": "com.avispl.symphony.api.dal.dto.control.AdvancedControllableProperty$Button","gracePeriod": "120000","labelPressed": "Rebooting..."}}]}
};
公共字典可控属性=新字典{
{“controllableProperties”,[{“name”:“Reboot”,“type”:{“@class”:“com.avispl.symphony.api.dal.dto.control.AdvancedControllableProperty$Button”,“gracePeriod”:“120000”,“labelPressed”:“Rebooting…”}}]}
};
但值不是字符串
我试过这样做
public Dictionary<string, string> controllableProperties = new Dictionary<string, string> {
{"controllableProperties", "[{"name": "Reboot","type": {"@class": "com.avispl.symphony.api.dal.dto.control.AdvancedControllableProperty$Button","gracePeriod": "120000","labelPressed": "Rebooting..."}}]"}
};
公共字典可控属性=新字典{
{“controllableProperties”、“[{”name:“Reboot”,“type:{”@class:“com.avispl.symphony.api.dal.dto.control.AdvancedControllableProperty$Button”,“gracePeriod:“120000”,“labelPressed:“Rebooting…”}]}
};
但这仍然是错误的
如何解决此问题?您需要在字符串中转义“
。一种方法是将它们替换为\”
:
字典可控属性=新字典
{
{
“可控属性”,
“[{\“name\”:“Reboot\”,“type\”:{\“@class\”:“com.avispl.symphony.api.dal.dto.control.AdvancedControllerableProperty$Button\”,“gracePeriod\”:“120000\”,“labelPressed\”:“Rebooting…”
}
};
Console.WriteLine(controllableProperties.Values.First());//打印[{“name”:“Reboot”,“type”:{“@class”:“com.avispl.symphony.api.dal.dto.control.AdvancedControllerableProperty$按钮”,“gracePeriod”:“120000”,“labelPressed”:“Rebooting…”
您的语法对于集合初始值设定项无效,并且字典
不是识别方括号的json。那么,我如何才能使其正确?因为我需要值为“”的JSON@PavelAnikhouski@EugeneSukh你需要转义你的json字符串。基本上用\“
替换里面的所有”
你应该像这样研究json `公共字典ControlableProperties=new Dictionary{{“ControlableProperties”,“[{\“name\”:\“Reboot\”\“type\”:{\“@class\”:\“com.avispl.symphony.api.dal.dto.control.AdvancedControllerableProperty$Button\”,“gracePeriod\”:“120000\”,“labelPressed\”:vRebooting…“}]”;`但现在我用\“
@GuruStron获得了JSON
Dictionary<string, string> controllableProperties = new Dictionary<string, string>
{
{
"controllableProperties",
"[{\"name\": \"Reboot\",\"type\": {\"@class\": \"com.avispl.symphony.api.dal.dto.control.AdvancedControllableProperty$Button\",\"gracePeriod\": \"120000\",\"labelPressed\": \"Rebooting...\"}}]"
}
};
Console.WriteLine(controllableProperties.Values.First()); // prints [{"name": "Reboot","type": {"@class": "com.avispl.symphony.api.dal.dto.control.AdvancedControllableProperty$Button","gracePeriod": "120000","labelPressed": "Rebooting..."}}]