2
我正在嘗試閱讀與DataContractJsonSerializer
一樣的JSON,正如我平時所做的那樣。InvalidCastException與DataContractJsonSerializer
有效的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);
而且我不知道爲什麼?
確保TFLBuses和NRResult具有不帶參數的公共構造函數。 – invalidusername
對不起,TFLBuses應該是'定時'。改變。 –