本文介绍了序列化我的实体时 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