问题
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