JavaScriptSerializer与自定义类型

10

我有一个返回类型为List的函数。我将其用于支持JSON的WebService中,如下所示:

  [WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<Product> GetProducts(string dummy)  /* without a parameter, it will not go through */
    {
        return new x.GetProducts();
    }
这将返回:
{"d":[{"__type":"Product","Id":"2316","Name":"Big Something ","Price":"3000","Quantity":"5"}]}

我需要在一个简单的aspx文件中使用这段代码,因此我创建了一个JavaScriptSerializer:

        JavaScriptSerializer js = new JavaScriptSerializer();
        StringBuilder sb = new StringBuilder();

        List<Product> products = base.GetProducts();
        js.RegisterConverters(new JavaScriptConverter[] { new ProductConverter() });
        js.Serialize(products, sb);

        string _jsonShopbasket = sb.ToString();

但是它没有返回类型:

[{"Id":"2316","Name":"Big One ","Price":"3000","Quantity":"5"}]

有人知道如何让第二个序列化工作,就像第一个一样吗?

谢谢!

3个回答

16

创建 JavaScriptSerializer 时,将 SimpleTypeResolver 的一个实例传递给它。

new JavaScriptSerializer(new SimpleTypeResolver())

无需创建自己的JavaScriptConverter。


有什么办法可以重命名“_type”属性以删除下划线吗? - tobiak777

3

好的,我已经有解决方法了,我手动将__type添加到JavaScriptConverter类中的集合中。

    public class ProductConverter : JavaScriptConverter
{        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        Product p = obj as Product;
        if (p == null)
        {
            throw new InvalidOperationException("object must be of the Product type");
        }

        IDictionary<string, object> json = new Dictionary<string, object>();
        json.Add("__type", "Product");
        json.Add("Id", p.Id);
        json.Add("Name", p.Name);
        json.Add("Price", p.Price);

        return json;
    }
}

有没有官方的方法来做这个呢? :)

2

在Joshua的回答基础上,您需要实现一个SimpleTypeResolver。

以下是我使用的“官方”方法。

1)创建这个类:

using System;
using System.Web;
using System.Web.Compilation;
using System.Web.Script.Serialization;

namespace XYZ.Util
{
    /// <summary>
    /// as __type is missing ,we need to add this
    /// </summary>
    public class ManualResolver : SimpleTypeResolver
    {
        public ManualResolver() { }
        public override Type ResolveType(string id)
        {
            return System.Web.Compilation.BuildManager.GetType(id, false);
        }
    }
}

2)使用它进行序列化

var s = new System.Web.Script.Serialization.JavaScriptSerializer(new XYZ.Util.ManualResolver());
string resultJs = s.Serialize(result);
lblJs.Text = string.Format("<script>var resultObj = {0};</script>", resultJs);

3) 使用它进行反序列化

System.Web.Script.Serialization.JavaScriptSerializer(new XYZ.Util.ManualResolver());
var result = json.Deserialize<ShoppingCartItem[]>(jsonItemArray);

完整文章在这里:http://www.agilechai.com/content/serialize-and-deserialize-to-json-from-asp-net/

此篇文章涉及it技术,介绍了如何在ASP.NET中将数据序列化为JSON格式并反序列化回来。如果你需要使用这种格式来传输数据,可以参考本文学习其实现方法。

sharpdeveloper.net已经关闭。当您在解决问题时,遇到一个潜在的可以解决头痛的答案链接失效时,这是非常恼人和令人沮丧的。请大家!只需将信息复制/粘贴到这里即可! - JayRO-GreyBeard
@JayRO-GreyBeard修复了链接。 - Sameer Alibhai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接