如何在Json中解析多个记录

时间:2013-11-25 01:20:31

标签: c# .net json parsing

您好我正在尝试将Json响应解析为一个类。所以这里是响应的样子......

[{"id":103,"customer_id":0},{"id":110,"customer_id":1}]

我能够解析一行(我删除了'['']'并将其放入一个类中)。问题是当我有多个记录,像这样,我有一个问题。这就是我解析数据的方式......

        [DataContract]
public class Order
{
    public List<OrderRow> Orders { get; set; }
}

[DataContract]
public class OrderRow
{
    [DataMember(Name = "id")]
    public int id { get; set; }
    [DataMember(Name = "customer_id")]
    public int customer_id { get; set; }
}

StreamReader jfile = new StreamReader(@"path\test.json");
string json = jfile.ReadToEnd();
jfile.Close();

byte[] bytes = Encoding.UTF8.GetBytes(json);
MemoryStream mStream = new MemoryStream(bytes);

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Order));
Order jsonOrder = (Order)serializer.ReadObject(mStream);

1 个答案:

答案 0 :(得分:3)

尝试将其直接反序列化为Order数组,而不是创建OrderRow[]类:

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(OrderRow[]));
OrderRow[] jsonOrderRows = (OrderRow[])serializer.ReadObject(mStream);