JavaScriptSerializer.Deserialize array

2020-08-09 07:13发布

问题:

I'm having trouble deserializing an array in .NET MVC3, any help would be appreciated.

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.

"[
{\"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?

回答1:

You should deserialize your json string to type List<BigCommerceOrderProduct>. No need for BigCommerceOrderProducts class

var myobj = jsSerializer.Deserialize<List<BigCommerceOrderProduct>>(jsonData);


回答2:

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}]}

    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();