序列化我的实体时

序列化我的实体时

本文介绍了序列化我的实体时,Json.Net意外字符("\")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用出色的Json.Net库来序列化由实体框架生成的实体.我使用以下代码来做到这一点:

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 "\" ?

推荐答案

我找到了在字符串("\")中使用转义字符的原因.序列化对象后,我将通过WCF将JSON字符串返回到客户端应用程序.显然,在将其发送到网络之前,WCF会自动将这些字符添加到字符串中.这是默认行为,显然是强制性的.

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.

由于我不希望这些转义字符,因此解决方法是将服务的返回类型更改为Stream,因此,将您的JSON字符串返回到内存流中.它运行完美,速度很快.

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.

这篇关于序列化我的实体时,Json.Net意外字符("\")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 18:31