JavaScriptSerializer with custom Type

我是研究僧i 提交于 2019-11-28 09:16:14

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

new JavaScriptSerializer(new SimpleTypeResolver())

No need to create your own JavaScriptConverter.

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?:)

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!