everybody
I have a json serialize problem for dictionary property name
This is my codes:
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);
I will get the result:
{
"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"
}
}
}
How to I serialize it without dictionary's property name like:
{
"A":"A_Value",
"B":"B_Value",
"CS1":{
"C1":"CS1_C1_Value",
"C2":"CS1_C2_Value"
},
"CS2":{
"C1":"CS2_C1_Value",
"C2":"CS2_C2_Value"
}
}
I tried remove the property of serialized result, then add the serialized dictionary data
Have easier way to solve it?
If you are willing to convert the dictionary to Dictionary<string, object>
you can use [JsonExtensionData]
attribute
public class MyClass
{
public string A { get; set; }
public string B { get; set; }
[JsonExtensionData]
public Dictionary<string, object> CS { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With