DataContractJsonSerializer的InvalidCastException

时间:2011-11-28 20:23:28

标签: c# .net json windows-phone-7

我正在尝试用DataContractJsonSerializer读取一些JSON,就像我通常那样。

有效的JSON如下:

  {
"error": "false",
"errorMsg": "Error message",
"errorField": "",
"time": "19:24",
"times": [
    [
        "blank",
        "19:35",
        "London",
        "direct",
        "1",
        "new"
    ],
    [
        "blank",
        "20:07",
        "Manchester",
        "direct",
        "1",
        "old"
    ]
],
"buses": [],
"ferries": [],
"updates": []
 }

C#

 DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(NRResult));

                using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(result1)))
                {
                    var item = (NRResult)serializer.ReadObject(stream);
                   foreach (var item in routes.Timings)
                    {
                        NRData _item = new NRData();

                        _item.Route = route.unknown1;
                        _item.Direction = route.time;
                        _item.Time = route.destination;
                        _item.AimedDepart = route.ontime;
                        _item.ExpectedDepart = route.unknown2;
                        _item.OpRef = route.link;

                        listBox1.Items.Add(_item);
                    } 

数据类:

 [DataContract]
public class NRResult
{
    [DataMember(Name = "times")]
    public IEnumerable<Timings> Timings{ get; set; }
}
[DataContract]

public class Timings    {
    [DataMember]
    public string unknown1 { get; set; }
    [DataMember]
    public string time { get; set; }
    [DataMember]
    public string destination { get; set; }
    [DataMember]
    public string ontime { get; set; }
    [DataMember]
    public string unknown2 { get; set; }
    [DataMember]
    public string link { get; set; }
}

我在线上得到InvalidCastException var item = (NRResult)serializer.ReadObject(stream); 我不确定为什么?

1 个答案:

答案 0 :(得分:2)

我认为NRResult的声明应该是这样的。

[DataContract]
public class NRResult
{
    [DataMember(Name = "times")]
    public IEnumerable<string[]> Timings { get; set; }
}

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(NRResult));
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(result1)))
{
    var item = (NRResult)serializer.ReadObject(stream);
    foreach (var route in item.Timings)
    {
        var _item = new{
                Route = route[0],
                Time = route[1],
                Destination = route[2],
                AimedDepart = route[3],
                ExpectedDepart = route[4],
                OpRef = route[5]
            };

        Console.WriteLine(_item);
    }
};