具有自定义类型的 JavaScriptSerializer

发布于 2024-07-25 02:16:18 字数 1051 浏览 7 评论 0原文

我有一个带有 List 返回类型的函数。 我在支持 JSON 的 WebService 中使用它,例如:

 [WebMethod(EnableSession = true)] 
      [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
      公开列表<产品>   GetProducts(string dummy) /* 不带参数,不会遍历 */ 
      { 
          返回新的 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"}]

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

谢谢!

I have a function with a List return type. I'm using this in a JSON-enabled WebService like:

  [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();
    }

this returns:

{"d":[{"__type":"Product","Id":"2316","Name":"Big Something ","Price":"3000","Quantity":"5"}]}

I need to use this code in a simple aspx file too, so I created a 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();

but it returns without a type:

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

Does anyone have any clue how to get the second Serialization work like the first?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

哀由 2024-08-01 02:16:18

创建 JavaScriptSerializer 时,向其传递 SimpleTypeResolver 的实例。

new JavaScriptSerializer(new SimpleTypeResolver())

无需创建您自己的 JavaScriptConverter。

When you create the JavaScriptSerializer, pass it an instance of SimpleTypeResolver.

new JavaScriptSerializer(new SimpleTypeResolver())

No need to create your own JavaScriptConverter.

呆° 2024-08-01 02:16:18

好的,我有解决方案,我已手动将 __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;
    }
}

有没有任何“官方”方法可以做到这一点?:)

Ok, I have the solution, I've manually added the __type to the collection in the JavaScriptConverter class.

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

Is there any "offical" way to do this?:)

墨离汐 2024-08-01 02:16:18

基于约书亚的答案,您需要实现一个 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/

Building on Joshua's answer, you need to implement a SimpleTypeResolver

Here is the "official" way that worked for me.

1) Create this class

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) Use it to serialize

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) Use it to deserialize

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

Full post here: http://www.agilechai.com/content/serialize-and-deserialize-to-json-from-asp-net/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文