Trouble Serializing To JSON Using JavaScriptSerializer

孤街浪徒 提交于 2019-12-08 07:37:46

问题


I'm having some trouble serializing an object to a JSON string using System.Web.Script.Serialization.JavaScriptSerializer. Whenever I try to do it, my strings are automatically html encoded. Is there a way to prevent this from happening? I'd really like to avoid using an external library if possible (code is for .NET 4). Here's my code:

class Program
{
    static void Main(string[] args)
    {
        string myHtml = "<div class=\"blueBackground\">This is a really cool div:)</div>";
        int someOtherValue = 5;

        var jsonSerializer = new JavaScriptSerializer();

        string jsonObj = jsonSerializer.Serialize(new MyClass
        {
            StringProperty = myHtml,
            IntProperty = someOtherValue
        });

        Console.WriteLine(jsonObj);
        Console.ReadLine();
    }

    class MyClass
    {
        public string StringProperty { get; set; }
        public int IntProperty { get; set; }
    }
}

It outputs the string

{"StringProperty":"\u003cdiv class=\"blueBackground\"\u003eThis is a really cool div:)\u003c/div\u003e","IntProperty":5}

Thanks!


回答1:


Your strings are not HTML encoded. They are javascript encoded. JSON is intended to be read by javascript interpreters and your output is perfectly valid javascript as seen in this live demo. It's valid JSON and any standard JSON deserializer will be able to understand this output and deserialize it back to the original string. So nothing to worry about.



来源:https://stackoverflow.com/questions/10390819/trouble-serializing-to-json-using-javascriptserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!