7

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?

1

1 Answer 1

9

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; }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, it working now
Using JsonExtensionData sometimes throw exception about: "implementation of IDictionary<string, JToken>" In my case it works without that attribute just Dictionary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.