gpt4 book ai didi

c# - 带有 DataContractJsonSerializer 的 InvalidCastException

转载 作者:太空宇宙 更新时间:2023-11-03 11:29:31 24 4
gpt4 key购买 nike

我正尝试像往常一样使用 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; }
}

我在该行收到一个 InvalidCastExceptionvar 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com