Search code examples
asp.netjavascriptserializer

JavaScriptSerializer with custom Type


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!


Solution

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