使用的JavaScriptSerializer自定义类型 [英] JavaScriptSerializer with custom Type
本文介绍了使用的JavaScriptSerializer自定义类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表返回类型的函数。我在支持JSON的WebService的使用本这样的:
[的WebMethod(EnableSession =真)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)
公开名单<产品与GT;的GetProducts(字符串虚拟)/ *没有参数,它不会通过* /
{
返回新x.GetProducts();
}
块引用>这将返回:
{D:[{__类型:产品,ID:2316,名:大东西,价格:3000 ,数量:5}]}
我需要一个简单的aspx文件也使用这个code,所以我创建了一个的JavaScriptSerializer:
的JavaScriptSerializer JS =新的JavaScriptSerializer();
StringBuilder的SB =新的StringBuilder(); 清单<产品与GT;产品= base.GetProducts();
js.RegisterConverters(新JavaScriptConverter [] {新ProductConverter()});
js.Serialize(产品,某人); 字符串_jsonShopbasket = sb.ToString();但它返回无类型:
[{ID:2316,姓名:大一号,价格:3000,量:5}]
没有人有任何线索如何获得第二个序列化的工作像第一?
谢谢!
解决方案好吧,我有解决方案,我已经手动添加在 __类型可在 JavaScriptConverter 类。
公共类ProductConverter:JavaScriptConverter
{公众覆盖的IDictionary<字符串对象>序列化(obj对象,序列化的JavaScriptSerializer)
{
产品p = OBJ的产品;
如果(P == NULL)
{
抛出新的InvalidOperationException异常(对象必须是产品类型);
} IDictionary的<字符串对象> JSON =新词典<字符串对象>();
json.Add(__类型,产品);
json.Add(ID,p.Id);
json.Add(名,p.Name);
json.Add(价格,p.Price); 返回JSON;
}
}有没有官方的方式来做到这一点?)
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!
解决方案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?:)
这篇关于使用的JavaScriptSerializer自定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文