1

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 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, thanks Darin:) I had no idea there even was such a thing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.