5

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?

Max
  • 4,439
  • 2
  • 18
  • 32
  • Sounds like you want something like `[JsonTypedExtensionData]` from [How to deserialize a child object with dynamic (numeric) key names?](https://stackoverflow.com/a/40094403/3744182). – dbc Jul 27 '17 at 10:19

1 Answers1

8

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; }
}
Guy
  • 46,488
  • 10
  • 44
  • 88