【发布时间】:2018-11-06 00:39:45
【问题描述】:
我正在尝试用 c# 中的 newtosoft json 反序列化以下 json 对象:
{
"address": "address",
"id": 1,
"latitude": 46.0757062,
"longitude": 18.1975697,
"name": "store name",
"openingHours": [
{
"closeing": "01:00:00",
"opening": "11:00:00",
"weekday": 1
}
]
}
我的班级是这样的:
[PrimaryKey, JsonProperty("id")]
public int Id { get; }
[JsonProperty("name"), Column("name")]
public string Name { get; }
[JsonProperty("latitude"), Column("latitude")]
public double Latitude { get; }
[JsonProperty("longitude"), Column("longitude")]
public double Longitude { get; }
[JsonProperty("openingHours"), Ignore]
public List<OpeningHours> Openinghours { get; set; }
OpeningHours 类:
public class OpeningHours
{
[JsonProperty("weekday")]
public int Day { get; set; }
[JsonProperty("opening")]
public TimeSpan Open { get; set; }
[JsonProperty("closeing")]
public TimeSpan Close { get; set; }
}
这是尝试反序列化的方法:
var result = JsonConvert.DeserializeObject<T>(json); //<-- this one should be the correct
var result = JsonConvert.DeserializeObject<T[]>(json);
var result = JsonConvert.DeserializeObject<List<T>>(json);
每次遇到这样的错误:
Newtonsoft.Json.JsonSerializationException:无法反序列化 当前 JSON 数组(例如 [1,2,3])转换为类型 'System.Collections.Generic.Dictionary`2[System.String,xMarksThePub.Model.OpeningHours]' 因为该类型需要一个 JSON 对象(例如 {"name":"value"}) 正确反序列化。要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为 实现集合接口的数组或类型(例如 ICollection, IList) 之类的可以从 JSON 反序列化的 List 大批。 JsonArrayAttribute 也可以添加到类型中以强制它 从 JSON 数组反序列化。路径“openingHours”,第 1 行,位置 137.
Pub 是我班级的名字。
我不知道我做错了什么。
【问题讨论】:
-
能否请您显示“开放时间”课程?
-
如果您提供实际可运行的代码,那么完整的类等会很有帮助。
-
我认为您没有显示实际引发错误的代码。您错误地说您正在尝试将''反序列化为类型'System.Collections.Generic.Dictionary`2'',您的代码中根本没有字典类型