Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.NET Serialize dictionary without property name [duplicate]

Tags:

json

c#

json.net

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?

like image 446
Max Avatar asked Jul 27 '17 10:07

Max


1 Answers

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; }
}
like image 184
Guy Avatar answered Oct 15 '22 13:10

Guy