C# JavaScriptSerializer.Deserialize 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9033730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScriptSerializer.Deserialize array
提问by Dean
I'm having trouble deserializing an array in .NET MVC3, any help would be appreciated.
我在 .NET MVC3 中反序列化数组时遇到问题,任何帮助将不胜感激。
Here's the code snippet:
这是代码片段:
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);
}
Here's the subset of the data string returned by JSON as jsonData. I've remove extra fields.
这是 JSON 作为 jsonData 返回的数据字符串的子集。我已经删除了额外的字段。
"[
{\"id\":33,\"order_id\":230025,...},
{\"id\":34,\"order_id\":230025,...}
]"
Here are the objects:
以下是对象:
[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; }
...
}
I'm getting this error:
我收到此错误:
"Type 'Pxo.Models.BigCommerce.BigCommerceOrderProducts' is not supported for deserialization of an array.
Any ideas?
有任何想法吗?
采纳答案by L.B
You should deserialize your json string to type List<BigCommerceOrderProduct>. No need for BigCommerceOrderProductsclass
您应该将 json 字符串反序列化为 type List<BigCommerceOrderProduct>。不需要BigCommerceOrderProducts上课
var myobj = jsSerializer.Deserialize<List<BigCommerceOrderProduct>>(jsonData);
回答by Chris Gessler
This little proggy works fine for me. Could be something unexpected in the response stream.
这个小程序对我来说很好用。响应流中可能出现意外情况。
The json output is: {"Data":[{"Id":33,"Order_id":230025},{"Id":34,"Order_id":230025}]}
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();

