简体   繁体   English

序列化我的实体时 Json.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.我正在使用优秀的 Json.Net 库来序列化由实体框架生成的实体。 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 "\\" ?有人知道为什么以及如何摆脱这些转义字符斜线 "\\" 吗?

I suspect it's not actually adding escape characters at all.我怀疑它实际上根本没有添加转义字符。 I suspect you're just looking at the string in a debugger, and that's adding the escaping.我怀疑您只是在调试器中查看字符串,这就是在添加转义。

Try dumping it to a file or the console.尝试将其转储到文件或控制台。

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.序列化对象后,我通过 WCF 将 JSON 字符串返回给客户端应用程序。 Apparently, WCF is automatically adding these characters to the string before sending it to the network.显然,WCF 在将字符串发送到网络之前会自动将这些字符添加到字符串中。 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.由于我不想要这些转义字符,因此解决方法是将服务的返回类型更改为 Stream 等,在内存流中返回您的 JSON 字符串。 It works perfectly and is quite fast.它工作得很好,而且速度非常快。

It's invalid JSON because the result of serializing a list of objects is an array, ie, the json will start with a [ and ending with a ] .它是无效的 JSON,因为序列化对象列表的结果是一个数组,即 json 将以[开头并以]结尾。 To fix this, you need to wrap the list of objects in a root object (any instance of a class or an anonymous object), so, the resulting string will start with a { and end with } .要解决此问题,您需要将对象列表包装在根对象(类的任何实例或匿名对象)中,因此,结果字符串将以{开头并以}结尾。

For example:例如:

var output = new List<object>();
var json = JsonConvert.SerializeObject(new { root = output }, Formatting.Indented);
Response.Write(json);

Does this one help?这个有用吗? I used it in my WebService to return Json content:我在我的 WebService 中使用它来返回 Json 内容:

private HttpContent ConvertToJsonContent(object content)
{
  string jsonObject = JsonConvert.SerializeObject(content, Newtonsoft.Json.Formatting.Indented);
  return new StringContent(jsonObject, Encoding.UTF8, "application/json");
}

If strings have a "\\" the two "\\\\" will come back.如果字符串有一个“\\”,两个“\\\\”就会回来。 You can avoid this by using Unescape您可以通过使用 Unescape 来避免这种情况

private HttpContent ConvertToJsonContent(object content)
{
  string jsonObject = Regex.Unescape(JsonConvert.SerializeObject(content, Newtonsoft.Json.Formatting.Indented));
  return new StringContent(jsonObject, Encoding.UTF8, "application/json");
}

I should note that you have not completely quoted the outputted stuff (I got the url to work in your answer - that should have been edited into your question rather than put as an answer).我应该注意到您没有完全引用输出的内容(我得到了可以在您的答案中使用的网址 - 应该将其编辑到您的问题中而不是作为答案)。 The string I got back in a file was this:我在文件中返回的字符串是这样的:

"[{\"$id\":\"1\",\"CreationDate\":\"\\\/Date(1293186324257+0000)\\\/\",\"ImageUrl\":\"http:\/\/www.c-tina.com\/MyVoucherAdmin\/Images\/shop22\/burger.jpg\",\"Title\":\"Get one burger for free\",\"Description\":\"Bla lbzlfpzkfgmzke\\rdmjdgmj\\r\\r\\rlgfpzkegmkzepk\",\"ShopId\":22,\"PromotionId\":15,\"Shop\":null,\"Features\":[],\"SingleStats\":[],\"WhatsHots\":[],\"EntityKey\":{\"$id\":\"2\",\"EntitySetName\":\"Promotions\",\"EntityContainerName\":\"MyVoucherEntities\",\"EntityKeyValues\":[{\"Key\":\"PromotionId\",\"Type\":\"System.Int32\",\"Value\":\"15\"}]}}]"

the key thing to me is that there are unescaped quotes at the front and end which makes me think that whatever is outputting it is deciding it needs to be quoted and if you are surrounding it in quotes you ahve to escape the quotes that are inside it.对我来说,关键是前端和末尾都有未转义的引号,这让我认为无论输出的是什么,都决定需要引用它,如果你用引号将它括起来,你必须转义它里面的引号.

Without seeing the full output its hard to say if the problem is in teh code you've quoted above to generate the JSON or if there is a problem at a later step of processing this which is causing the quoting.如果没有看到完整的输出,很难说问题是否出在您上面引用的代码中以生成 JSON,或者在处理此问题的后续步骤中是否存在导致引用的问题。 Have you debugged and confirmed that the output of your serialize call is definitely producing the escaped version rather than it being done at a later stage potentially?您是否已调试并确认序列化调用的输出肯定会生成转义版本,而不是可能在稍后阶段完成? If you're not used to the debugger then pay attention to Jon Skeet's suggest of dumping it to file or console to make sure there is no confusion that way.如果您不习惯调试器,请注意 Jon Skeet 将其转储到文件或控制台的建议,以确保不会出现混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM