Search code examples
c#serializationescapingjavascriptserializer

Backslash escaping issue


I have the following code:

search.UserToken = string.Format(@"{0};{1}", pi.Username, pi.Password)
JavaScriptSerializer jss = new JavaScriptSerializer();
string data = jss.Serialize(obj);

Where pi.Username consists of the domain\username. This object is then serialized using the JavaScriptSerializer before it's sent via a web request to an API.

The problem I have is that the value sent ends up with four backslashes between the domain and the username as on the creation of the string the initial single backslash is escaped and then both these are escaped again during serialization.

How do I prevent this so that it's not escaped twice?


Solution

  • I found a solution for your problem. You can check the code snippet below:

    [TestClass]
    public class JavascriptSerializerTest
    {
        [TestMethod]
        public void TestEscapeOnJavascriptSerializer()
        {
            const string replaceableToken = "[replace_here]";
            var user = @"domain\user".Replace(@"\", replaceableToken);
            const string password = "123456";
    
            var token = new Token { Value = string.Format("{0};{1}", user, password) };
            var serializer = new JavaScriptSerializer();
    
            var jsonObject = serializer.Serialize(token);
            jsonObject = jsonObject.Replace(replaceableToken, @"\");
            Assert.AreEqual("{\"Value\":\"domain\\user;123456\"}", jsonObject);
        }
    }
    
    public class Token
    {
        public string Value { get; set; }
    }
    

    Explanation

    The JavaScriptSerializer class calls internally the method HttpUtility.JavaScriptStringEncode(input), that adds the additional backslashes, by calling this method http://referencesource.microsoft.com/#System.Web/Util/HttpEncoder.cs,c0289ba7b2d459e5. Another option would be to replace the HttpEncoder, but it seems too much for me :-).