我正在尝试将 JSON 字符串反序列化为 ObservableCollection 对象,但 Json.net 抛出此错误
{"无法将当前 JSON 对象 (例如 {\"name\":\"value\"}) 反序列化为类型 'System.Collections.ObjectModel.ObservableCollection`1[ZenPanda.DataModel.Session]' 因为该类型需要 JSON数组(例如 [1,2,3])以正确反序列化。\r\n要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或将反序列化类型更改为可以从 JSON 对象反序列化的普通 .NET 类型(例如,不是整数之类的原始类型,不是数组或列表之类的集合类型)。也可以将 JsonObjectAttribute 添加到该类型以强制它从 JSON 对象反序列化。 \r\n路径“参数”,第 1 行,位置 13。"}
我的数据模型在下面
public class Session
{
[JsonProperty("arguments")]
public SessionProperties arguments { get; set; }
[JsonProperty("result")]
public string Result { get; set; }
[JsonProperty("tag")]
public int Tag { get; set; }
}
public class SessionProperties
{
[JsonProperty("alt-speed-down")]
public int Altspeeddown { get; set; }
[JsonProperty("alt-speed-enabled")]
public bool Altspeedenabled { get; set; }
[JsonProperty("alt-speed-time-begin")]
public int Altspeedtimebegin { get; set; }
[JsonProperty("alt-speed-time-day")]
public int Altspeedtimeday { get; set; }
[JsonProperty("alt-speed-time-enabled")]
public bool Altspeedtimeenabled { get; set; }
[JsonProperty("units")]
public SessionUnits Units { get; set; }
[JsonProperty("utp-enabled")]
public bool Utpenabled { get; set; }
}
public class SessionUnits
{
[JsonProperty("memory-bytes")]
public int Memorybytes { get; set; }
[JsonProperty("memory-units")]
public List<string> Memoryunits { get; set; }
}
这是调用 JsonConvert 的代码
public ObservableCollection<Session> currentSession = new ObservableCollection<Session>();
string sessionResponse = await task.Content.ReadAsStringAsync();
currentSession = JsonConvert.DeserializeObject<ObservableCollection<Session>>(sessionResponse);
这是原始 JSON
{"arguments": {"alt-speed-down":50,"alt-speed-enabled":false,"alt-speed-time-begin":540,"alt-speed-time-day":127,"alt-speed-time-enabled":false,
"units":{"memory-bytes":1024,"memory-units":["KiB","MiB","GiB","TiB"],"size-bytes":1000,"size-units":["kB","MB","GB","TB"],"speed- bytes":1000,"speed-units":["kB/s","MB/s","GB/s","TB/s"]},
"utp-enabled":true},
"result":"success",
"tag":568}
如果我将 currentSession 声明为普通的 Session 对象,那么 Json.net 会愉快地反序列化到该实例中,但是当我将其声明为 ObservableCollection 时,Json.net 会抛出错误。
如果这是一个完整的新手问题/问题,我对编程很抱歉。提前致谢!