麻烦序列化到JSON使用的JavaScriptSerializer [英] Trouble Serializing To JSON Using JavaScriptSerializer

查看:224
本文介绍了麻烦序列化到JSON使用的JavaScriptSerializer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些麻烦序列化对象使用System.Web.Script.Serialization.JavaScriptSerializer一个JSON字符串。每当我尝试这样做,我的字符串自动连接HTML codeD。有情况发生的一种方式,以prevent呢?我真的想避免使用外部库如果可能的话(code是.NET 4)。这里是我的code:

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; }
    }
}

则输出

{StringProperty:\\ u003cdiv类= \\blueBackground \\\\ u003eThis是一个
  真的很酷格:)\\ u003c / DIV \\ u003e,IntProperty:5}

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

谢谢!

推荐答案

您字符串不是HTML连接codeD。他们是JavaScript的EN codeD。 JSON的目的是由JavaScript间preters阅读和你的输出是看到这种现场演示。它是有效的JSON和任何标准的JSON解串器就能明白这个输出和反序列化回原始字符串。所以没什么好担心的。

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.

这篇关于麻烦序列化到JSON使用的JavaScriptSerializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆