How to prevent '\' in json from being escaped

AnonymousKKYY 20 Reputation points
2025-04-01T08:13:32.0833333+00:00

There is a Json string that needs to be deserialized into an instance. The value of one of the properties is a string prefixed with [ \ ]. How can I keep this escape character [ \ ] in the instance?

    internal class Program
    {
        static void Main(string[] args)
        {
            string jsonString = "{\"name\": \"user\", \"id\": \"\dddd\"}";
            Student stu = JsonConvert.DeserializeObject<Student>(jsonString);
        }
    }
    class Student
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

The property "Id" of the "stu" should be "\dddd", rather than "dddd". How do I need to modify the property value for "id" in Json string.

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2025-04-01T08:32:14.0933333+00:00

    Hi @AnonymousKKYY ,Welcome to Microsoft Q&A,

    In JSON, the backslash (\) is a special character, so it needs to be written as \\ to represent a real \.

    In C# strings, the backslash is also a special character, so in C# code, the \\ in JSON needs to be escaped once more, written as \\\\.

    After JSON parsing, stu.Id will correctly contain \dddd without losing the backslash.

    string jsonString = "{\"name\": \"user\", \"id\": \"\\\\dddd\"}"; 
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.