You're not far; you need to do something like this:
[WebMethod]
public static string GetProducts()
{
// instantiate a serializer
JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
//optional: you can create your own custom converter
TheSerializer.RegisterConverters(new JavaScriptConverter[] {new MyCustomJson()});
var products = context.GetProducts().ToList();
var TheJson = TheSerializer.Serialize(products);
return TheJson;
}
You can reduce this code further but I left it like that for clarity. In fact, you could even write this:
return context.GetProducts().ToList();
and this would return a json string. I prefer to be more explicit because I use custom converters. There's also Json.net but the framework's JavaScriptSerializer
works just fine out of the box.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…