Serialize complex dictionary with DataContractJsonSerializer

850 Views Asked by At

With .NET 4.5 version of DataContractJsonSerializer and with help of DataContractJsonSerializerSettings.UseSimpleDictionaryFormat I can serialize dictionaries. So for example this dictionary:

var dic = new Dictionary<string, object> 
{
  { "Level", 3 },
  { "Location", "Catacomb" }
};

will be converted into nice JSON:

{
  "Level":3,
  "Location":"Catacomb"
}

But if I have another dictionary as value:

var dic = new Dictionary<string, object> 
{
    { "Level", 3 },
    { "Location", new Dictionary<string, object> 
        {
            { "Name", "Catacobms" }
        }
    }
};

the the resulted JSON looks really bad:

{
   "Level":3,
   "Location":[
      {
         "__type":"KeyValuePairOfstringanyType:#System.Collections.Generic",
         "key":"Name",
         "value":"Catacobms"
      }
   ]
}

Is there any way to fix this problem?

PS: I know that there are other good JSON serializers, but in this case I need to use DataContractJsonSerializer.

1

There are 1 best solutions below

0
On

Try setting the EmitTypeInformation property on the serializer to EmitTypeInformation.Never

See MSDN Entry