具有自定义类型的 JavaScriptSerializer
我有一个带有 List 返回类型的函数。 我在支持 JSON 的 WebService 中使用它,例如:
[WebMethod(EnableSession = true)] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 公开列表<产品> GetProducts(string dummy) /* 不带参数,不会遍历 */ { 返回新的 x.GetProducts(); }
这返回:
{"d":[{"__type":"Product","Id":"2316","Name":"Big Something ","Price":"3000","Quantity":"5"}]}
我也需要在一个简单的 aspx 文件中使用此代码,所以我创建了一个 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();
但它返回时没有类型:
[{"Id":"2316","Name":"Big One ","Price":"3000","Quantity":"5"}]
有谁知道如何让第二个序列化像第一个一样工作?
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
创建 JavaScriptSerializer 时,向其传递 SimpleTypeResolver 的实例。
无需创建您自己的 JavaScriptConverter。
When you create the JavaScriptSerializer, pass it an instance of SimpleTypeResolver.
No need to create your own JavaScriptConverter.
好的,我有解决方案,我已手动将 __type 添加到 JavaScriptConverter 类中的集合中。
有没有任何“官方”方法可以做到这一点?:)
Ok, I have the solution, I've manually added the __type to the collection in the JavaScriptConverter class.
Is there any "offical" way to do this?:)
基于约书亚的答案,您需要实现一个 SimpleTypeResolver
这是对我有用的“官方”方法。
1) 创建此类
2) 使用它进行序列化
3) 使用它进行反序列化
完整帖子:http://www.agilechai.com/content/serialize-and-deserialize-to-json-from-asp-net/
Building on Joshua's answer, you need to implement a SimpleTypeResolver
Here is the "official" way that worked for me.
1) Create this class
2) Use it to serialize
3) Use it to deserialize
Full post here: http://www.agilechai.com/content/serialize-and-deserialize-to-json-from-asp-net/