简体   繁体   中英

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. 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. Maybe I am missing something else.

I am using Json.Net in a MVC4 WebApi project if that matters.

My data is coming back with \r\n in the string such as

  "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 . 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.

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).

What it worked was to parse the obtained json as a Token , and then use the token instead.

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. Like this:

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

I think this should work.

Regards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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