我正像往常一样尝试用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);
我不确定为什么吗?
最佳答案
我认为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);
}
};
关于c# - 具有DataContractJsonSerializer的InvalidCastException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8301832/