大家
我有字典属性名称
的json序列化问题这是我的代码:
public class MyClass
{
public string A { get; set; }
public string B { get; set; }
public Dictionary<string, C> CS { get; set; }
}
public class C
{
public string C1 { get; set; }
public string C2 { get; set; }
}
MyClass myObject = new MyClass()
{
A = "A_Value",
B = "B_Value",
CS = new Dictionary<string, C>
{
{"CS1", new C() { C1 = "CS1_C1_Value", C2 = "CS1_C2_Value" } },
{"CS2", new C() { C1 = "CS2_C1_Value", C2 = "CS2_C2_Value" } }
}
};
JsonConvert.SerializeObject(myObject);
我会得到结果:
{
"A":"A_Value",
"B":"B_Value",
"CS":{
"CS1":{
"C1":"CS1_C1_Value",
"C2":"CS1_C2_Value"
},
"CS2":{
"C1":"CS2_C1_Value",
"C2":"CS2_C2_Value"
}
}
}
如何在没有字典的属性名称的情况下对其进行序列化,如:
{
"A":"A_Value",
"B":"B_Value",
"CS1":{
"C1":"CS1_C1_Value",
"C2":"CS1_C2_Value"
},
"CS2":{
"C1":"CS2_C1_Value",
"C2":"CS2_C2_Value"
}
}
我尝试删除序列化结果的属性,然后添加序列化字典数据
有更简单的方法来解决它吗?
答案 0 :(得分:3)
如果您愿意将字典转换为Dictionary<string, object>
,则可以使用[JsonExtensionData]
属性
public class MyClass
{
public string A { get; set; }
public string B { get; set; }
[JsonExtensionData]
public Dictionary<string, object> CS { get; set; }
}