我有一个列表返回类型的函数。 我在支持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"}]
没有人有任何线索如何获得第二个序列化的工作像第一?
谢谢!
当您创建的JavaScriptSerializer,通过它SimpleTypeResolver的一个实例。
new JavaScriptSerializer(new SimpleTypeResolver())
无需创建自己的JavaScriptConverter。
好吧,我有解决方案,我已经手动在JavaScriptConverter类添加__type到集合。
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;
}
}
是否有任何“官方”的方式来做到这一点?:)
约书亚的答案的基础上,你需要实现一个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/