JavaScriptSerializer with custom Type

Posted by balint on Stack Overflow See other posts from Stack Overflow or by balint
Published on 2009-06-22T13:03:51Z Indexed on 2010/04/23 19:33 UTC
Read the original article Hit count: 639

Hi, 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!

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about javascriptserializer