您可以使用DataContractJsonSerializer 类,它是System.Runtime.Serialization 程序集的一部分。首先编写一个代表该实体的模型:
public class MyModel
{
public decimal Demand { get; set; }
public decimal Supply { get; set; }
public DateTime Date { get; set; }
public string DateString { get; set; }
}
然后将 JSON 字符串反序列化为这个模型的列表:
string json = "[{ \"Demand\": 4422.45, \"Supply\": 17660, \"Date\": \"/Date(1236504600000)/\", \"DateString\": \"3 PM\" }, { \"Demand\": 4622.88, \"Supply\": 7794, \"Date\": \"/Date(1236522600000)/\", \"DateString\": \"8 PM\" }, { \"Demand\": 545.65, \"Supply\": 2767, \"Date\": \"/Date(1236583800000)/\", \"DateString\": \"1 PM\" }, { \"Demand\": 0, \"Supply\": 1, \"Date\": \"/Date(1236587400000)/\", \"DateString\": \"2 PM\" }]";
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<MyModel>));
using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
List<MyModel> models = (List<MyModel>)serializer.ReadObject(stream);
foreach (MyModel model in models)
{
// do something with the model here
Console.WriteLine(model.Date);
}
}
更新:
看起来您正在使用一些不支持自动属性的史前版本的 C#。在这种情况下,每个属性都需要一个私有字段:
public class MyModel
{
private decimal demand;
public decimal Demand
{
get { return this.demand; }
set { this.demand = value; }
}
private decimal supply;
public decimal Supply
{
get { return this.supply; }
set { this.supply = value; }
}
private DateTime date;
public DateTime Date
{
get { return this.date; }
set { this.supply = value; }
}
private string dateString;
public string DateString
{
get { return this.dateString; }
set { this.dateString = value; }
}
}