简体   繁体   English

使用 Json.Net 处理数据中的换行符

[英]Handling newlines in data with Json.Net

Is there any way to handle newlines in JSON.NET. I have some data coming back with Carriage Return Line Feed in it and Json.Net is just leaving it raw in the return value.有什么方法可以处理 JSON.NET 中的换行符。我有一些数据返回,其中包含回车换行符,而 Json.Net 只是将其保留在返回值中。 Is there a way to force Json.Net to encode this for Json. I assumed this would happen by default but it is not happening for me.有没有办法强制 Json.Net 将其编码为 Json。我假设默认情况下会发生这种情况,但它不会发生在我身上。 Maybe I am missing something else.也许我还缺少其他东西。

I am using Json.Net in a MVC4 WebApi project if that matters.如果重要的话,我在 MVC4 WebApi 项目中使用 Json.Net。

My data is coming back with \r\n in the string such as我的数据在字符串中返回 \r\n ,例如

  "Keywords": "These are my keywords.\r\n\r\n\r\nThis is a second line...\r\n\r\nThis is a third line. ...\r\n\r\n\r\nThis is a 4th line ..."

From what I understand, that should be \\r\\n .据我了解,那应该是\\r\\n It could be a problem with the data I am returning, but I just wanted to see what JSON.NET should be doing with this.这可能是我返回的数据有问题,但我只是想看看 JSON.NET 应该用这个做什么。

For me, the problem was that even if the serialized Json object look correct in the debugger, when I write it to file it gets all thise literals added (ie backslashes are added).对我来说,问题是即使序列化的 Json object 在调试器中看起来是正确的,当我将它写入文件时它会添加所有这些文字(即添加反斜杠)。

What it worked was to parse the obtained json as a Token , and then use the token instead.它的作用是将获得的 json 解析为Token ,然后使用该 token 代替。

For example:例如:

// Serialize and convert to Token
string json = Newtonsoft.Json.JsonConvert.SerializeObject(someObject);
var token = JToken.Parse(json);

// Save to file
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(filepath, token);

I honestly do not understand why this would be needed, or if there is a better way around this.老实说,我不明白为什么需要这样做,或者是否有更好的解决方法。 Feedback in comment is appreciated.感谢评论中的反馈。

You can serialize your object with the option Formatting.Indented. 您可以使用Formatting.Indented选项序列化对象。 Like this: 像这样:

string yourJsonString = JsonConvert.SerializeObject(yourObject,  Formatting.Indented, new JsonSerializerSettings { });

I think this should work. 我认为这应该有效。

Regards. 问候。

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

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