JavaScriptSerializer with custom Type

balint picture balint · Jun 22, 2009 · Viewed 10.4k times · Source

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!

Answer

Joshua Flanagan picture Joshua Flanagan · Aug 14, 2009

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

new JavaScriptSerializer(new SimpleTypeResolver())

No need to create your own JavaScriptConverter.