When serializing my entities using Json.Net, I get unexpected characters ("").

c# entity-framework json.net wcf

Question

I serialize the entities created by entity framework using the amazing Json.Net package. To achieve this, I use the following code:

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

The objects are appropriately serialized, so everything works okay, but for the escape characters "," which give me nightmares while deserializing on the client side.

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

Does anybody know the cause of this or how to remove the escape letters ""?

1
23
7/19/2018 2:57:21 PM

Accepted Answer

I discovered the cause of my string's escape characters."\" ). I am using a WCF to return the JSON string to the client app after serializing my objects. These characters seem to be automatically added to the string before it is sent to the network by WCF. It is a natural tendency and seems to be required.

The remedy is to switch the service's return type to Stream and return your JSON text as a RAM stream since I didn't want these escape characters. It is really quick and works properly.

17
7/19/2018 3:00:22 PM

Popular Answer

I have a suspicion that it isn't even actually inserting escape characters. I think all you're doing is looking at the string in a debugger and adding the escaping with that's.

Consider dumping it to the console or a file.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow