System.Web.Script.Serialization.JavaScriptSerializer.Deserialize returns javascipt boolean literals (true,false) as strings of inappropriate initial upper case (True,False) RRS feed

  • Question

  • In a simple example my browser client sends JSON "true" or "false" to my C# server. 

    In C# I use System.Web.Script.Serialization.JavaScriptSerializer.Deserialize to get string values for the JSON content.  For the Javascript boolean literals, System.Web.Script.Serialization.JavaScriptSerializer.Deserialize returns initial caps values True or False.  This is unexpected as in the Javascript language, these boolean literals are specifically lower case.

    Here's a simple code snippet showing this problem:

                string res = new System.Web.Script.Serialization.JavaScriptSerializer ().Deserialize<string> ( "true" );

    You will find res == "True"; I expect it to be a valid Javascript value such as "true" (i.e. in lower case).

                string res = new System.Web.Script.Serialization.JavaScriptSerializer ().Deserialize<string> ( "false" );

    and here you will find res == "False"; I expect it to be a valid Javascript value such as "false" (i.e. in lower case)

    This looks like a bug to me or else I fail to grasp what justification there could be to return strings whose values are not natural to Javascript/JSON.  (And even C# uses lower case True and False.)  If you tried to send such strings back to the browser you'd have troubles.

    Best regards,


    According to "http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf"

    7.8.2 Boolean Literals
    BooleanLiteral :: true false

    Saturday, April 5, 2014 10:51 PM


  • Probably this is an expected behaviour. The values true and false are interpreted as Boolean JavaScript literals, however you ask for strings using Deserialize<string>. Then the system converts the result to string, which in case of Boolean.ToString() gives “True” and “False” by design. If you need Booleans, then use Deserialize<bool>. If you want exact strings, then the serialized strings should contain quotation marks: “\”true\”” and “\”false\””.

    • Marked as answer by Fred Bao Wednesday, April 16, 2014 6:32 AM
    Sunday, April 6, 2014 11:11 AM