This is my code to get blog,
[HttpGet("blog/{blog_id}")]
[AllowAnonymous]
public async Task<IActionResult> get_blog(string blog_id)
{
var blog = await _blogs.Find(b => b.id == blog_id).FirstOrDefaultAsync();
Console.WriteLine(blog.en_content);
if (blog == null) return NotFound("Blog not found.");
// return Ok(blog.en_content);
return Ok(blog);
}
Both Console.WriteLine(blog.en_content)
and return Ok(blog.en_content)
can return required results like
{"blocks":[{"key":"51q6n","text":"The purpose of this website is multi-fold:","type":"unstyled","
but return Ok(blog)
{\"blocks\":[{\"key\":\"51q6n\",\"text\":\"The purpose of
I only need 1 slash, instead of 3 slashes.
public class Blog
{
[JsonPropertyName("id")]
public required string id { get; set; }
[JsonPropertyName("en_content")]
public required string en_content { get; set; }
[JsonPropertyName("cn_content")]
public required string cn_content { get; set; }
}
When returning the Blog
object from your API, it is serialized as JSON. JSON relies on some special characters, e.g. double quotes to signal start and end of strings in the JSON. If any of your string content contains a double quote (before the terminating one), the serializer "escapes" this double quote to signal that this is not the end of the string. It does so by putting a backslash in front of it.
The string en_content
stores JSON that has already been serialized and thus already contains backslashes in front of the double quote. When serializing the Blog
object, JSON encounters these special characters and escapes them again, so that \"
ends up with two more backslashes for escaping: \\\"
.
The client that receives the response will (most likely) deserialize the JSON and create an object from it so it can access the data easily. However, after the first deserialization, en_content
still contains JSON stored as string so that the client needs to deserialize it again if it wants to access it as an object.
If you want to avoid this, you need to store the contents of en_content
as sub-document (and not as a string with JSON data). This is easiest if the structure is known beforehand.
If you want to be flexible with the content of the en_content
property and do not want to query it, storing it as string with JSON content is an easy option with the drawback that you have to deserialize it on the client again.