我有一个List返回类型的函数。我在支持JSON的WebService中使用它,如:
[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(); }
返回:
{"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"}]
有没有人知道如何让第二个Serialization像第一个一样工作?
谢谢!
答案 0 :(得分:16)
创建JavaScriptSerializer时,将其传递给SimpleTypeResolver的实例。
new JavaScriptSerializer(new SimpleTypeResolver())
无需创建自己的JavaScriptConverter。
答案 1 :(得分:3)
好的,我有解决方案,我已经手动将 __ type 添加到 JavaScriptConverter 类中的集合中。
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;
}
}
有没有“官方”的方式来做这件事?:)
答案 2 :(得分:2)
基于Joshua的回答,您需要实现SimpleTypeResolver
这是对我有用的“官方”方式。
1)创建此类
using System;
using System.Web;
using System.Web.Compilation;
using System.Web.Script.Serialization;
namespace XYZ.Util
{
/// <summary>
/// as __type is missing ,we need to add this
/// </summary>
public class ManualResolver : SimpleTypeResolver
{
public ManualResolver() { }
public override Type ResolveType(string id)
{
return System.Web.Compilation.BuildManager.GetType(id, false);
}
}
}
2)用它来序列化
var s = new System.Web.Script.Serialization.JavaScriptSerializer(new XYZ.Util.ManualResolver());
string resultJs = s.Serialize(result);
lblJs.Text = string.Format("<script>var resultObj = {0};</script>", resultJs);
3)用它来反序列化
System.Web.Script.Serialization.JavaScriptSerializer(new XYZ.Util.ManualResolver());
var result = json.Deserialize<ShoppingCartItem[]>(jsonItemArray);
这里的完整帖子:http://www.agilechai.com/content/serialize-and-deserialize-to-json-from-asp-net/