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"}]

有谁知道如何让第二个序列化工作像第一个一样?

谢谢!

4

3 回答 3

16

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

new JavaScriptSerializer(new SimpleTypeResolver())

无需创建自己的 JavaScriptConverter。

于 2009-08-14T14:27:25.857 回答
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;
    }
}

有没有“官方”的方式来做到这一点?:)

于 2009-06-22T13:25:40.703 回答
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/

于 2010-04-23T19:32:29.857 回答