我在.NET MVC3中反序列化数组时遇到问题,我们将不胜感激。
以下是代码段:
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string jsonData = reader.ReadToEnd();
result = (BigCommerceOrderProducts)jsSerializer.Deserialize<BigCommerceOrderProducts>(jsonData);
}
这是JSON作为jsonData返回的数据字符串的子集。我删除了额外的字段。
"[
{\"id\":33,\"order_id\":230025,...},
{\"id\":34,\"order_id\":230025,...}
]"
以下是对象:
[Serializable]
public class BigCommerceOrderProducts {
public List<BigCommerceOrderProduct> Data { get; set; }
}
[Serializable]
public class BigCommerceOrderProduct {
public int Id { get; set; }
public int Order_id { get; set; }
...
}
我收到了这个错误:
"Type 'Pxo.Models.BigCommerce.BigCommerceOrderProducts' is not supported for deserialization of an array.
有什么想法吗?
答案 0 :(得分:46)
您应该将json字符串反序列化为List<BigCommerceOrderProduct>
类型。无需BigCommerceOrderProducts
类
var myobj = jsSerializer.Deserialize<List<BigCommerceOrderProduct>>(jsonData);
答案 1 :(得分:1)
这个小程序对我来说很好。可能是响应流中意外的事情。
json输出为:{“Data”:[{“Id”:33,“Order_id”:230025},{“Id”:34,“Order_id”:230025}]}
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
BigCommerceOrderProducts a = new BigCommerceOrderProducts();
a.Data = new List<BigCommerceOrderProduct>();
BigCommerceOrderProduct b = new BigCommerceOrderProduct();
b.Id = 33;
b.Order_id = 230025;
a.Data.Add(b);
b = new BigCommerceOrderProduct();
b.Id = 34;
b.Order_id = 230025;
a.Data.Add(b);
string x = jsSerializer.Serialize(a);
Console.WriteLine(x);
a = jsSerializer.Deserialize<BigCommerceOrderProducts>(x);
Console.WriteLine(a.Data[0].Order_id);
Console.ReadLine();