Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
708 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

new JavaScriptSerializer(new SimpleTypeResolver())

No need to create your own JavaScriptConverter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...