Search code examples
c#entity-frameworkwcfjson.net

Json.Net unexpected characters ("\") when serializing my entities


I am using the excellent Json.Net library to serialize my entities generated by entity framework. I use the following code to do so :

using (MyVoucherEntities context = new MyVoucherEntities())
{
  List<MyObject> list = context.MyObjects.ToList();
  string json = JsonConvert.SerializeObject(list);
}

Everything goes well I mean, the objects are correctly serialized except one think : it adds escape characters "\" that makes me having nightmare when deserializing on the client side.

 [
     {
         \"$id\": \"1\",
         \"CreationDate\": \"\\\/Date(1293186324257+0000)\\\/\",
        \"ImageUrl\": \"http:\/\/www.google.com\",
         \"Title\": \"Here is a title\"
     } ]

Does anybody know why and how I can get rid of these escape characters slash "\" ?


Solution

  • I found the reason why I had escape characters in my string ("\"). After serializing my objects, I am returning the JSON string to the client app through a WCF. Apparently, WCF is automatically adding these characters to the string before sending it to the network. It is a default behaviour and is apparently mandatory.

    As I didn't want these escape characters, the workaround is to change the return type of the service to Stream and so, returning your JSON string inside a memory stream. It works perfectly and is quite fast.