Renaud Renaud - 1 year ago 128
C# Question

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

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:\/\/\",
\"Title\": \"Here is a title\"
} ]

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

Thanks a lot !

Answer Source

Ok 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 behavior 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 quiet fast.

Thx @Jon Skeet and @Chris for your help !

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download