admin管理员组

文章数量:1418112

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; }
}

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; }
}
Share Improve this question edited Jan 31 at 8:20 Guru Stron 144k11 gold badges172 silver badges212 bronze badges asked Jan 31 at 7:36 Xi LuoXi Luo 231 silver badge4 bronze badges 6
  • I want to know the data type of variable blog. Is blog an entity object you created? For example you created Blog class with en_content property? Or it's just an object? – Tiny Wang Commented Jan 31 at 7:40
  • en_content is String type – Xi Luo Commented Jan 31 at 7:41
  • Could you pls edit your question to show what you are getting now, and what you want to get instead? – Tiny Wang Commented Jan 31 at 7:44
  • Thank you for your assistance. What I get now, is return Ok(blog) with 3 slashes. The mongoDB is also with 1 slash. – Xi Luo Commented Jan 31 at 7:45
  • Please bear with me, we can see that the content of en_content can be abstract as a List<block> which block here also has it's properties corresponding to the content of the result showed in the screenshot, why don't you create block entity to host the data? Does the block might have dynamic content so that you just want to save en_content as a string? By the way, do you want to remove all slashed in the response, or you want to keep 1 slash? – Tiny Wang Commented Jan 31 at 7:49
 |  Show 1 more comment

2 Answers 2

Reset to default 1

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.

I had a test with code below and this is my test result.

public async Task<IActionResult> getoutputs() {
    var temp = new Blog {
        id = "1",
        en_content = "{\"blocks\":[{\"key\":\"51q6n\",\"text\":\"The purpose of\"}]}",
    };
    var dict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(temp.en_content);
    var temp2 = new Blog2
    {
        id = "1",
        en_content = dict
    };
    //return Ok(temp); // {"id":"1","en_content":"{\"blocks\":[{\"key\":\"51q6n\",\"text\":\"The purpose of\"}]}"}
    return Ok(temp2);
    //return Ok(temp.en_content);//{"blocks":[{"key":"51q6n","text":"The purpose of"}]}
}

public class Blog
{
    public string id { get; set; }
    public string en_content { get; set; }
}

public class Blog2
{
    public string id { get; set; }
    public object en_content { get; set; }
}

The reason why we get {"id":"1","en_content":"{\"blocks\":[{\"key\":\"51q6n\",\"text\":\"The purpose of\"}]}"} for return Ok(temp); and get {"blocks":[{"key":"51q6n","text":"The purpose of"}]} for return Ok(temp.en_content); is related to how the response is serialized.

return Ok(temp) the Blog object is serialized to JSON, here en_content is a string so that in the response we could see the slash.

return Ok(temp.en_content) then en_content is serialized to JSON so that we can't see slashes in the result.

To remove all slashed in the result, we have to serialize string to JSON object ahead in c# code.

本文标签: NET return JSON without reformatingStack Overflow