【发布时间】:2021-05-20 20:01:20
【问题描述】:
我的数据看起来像这样,除了有 1000 个实体,而不仅仅是 2 个。
{
"1": {
"id": 1,
"name": "James",
"last_updated": "2021-04-26",
"incomplete": true,
"valid": true,
"start_date": "2007-03-20",
"items": 51,
"current": 1,
"hitpoints": 52
}
"2": {
"id": 2,
"name": "Peter",
"last_updated": "2021-04-25",
"incomplete": true,
"members": true,
"start_date": "2009-06-13",
"items": 51,
"current": 1,
"hitpoints": 52
}
}
我的代码是这样的:
try
{
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
var dict = JsonConvert.DeserializeObject<Dictionary<string, Entry>>(json, settings);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
这是我得到的错误:
Newtonsoft.Json.JsonSerializationException:将值 {null} 转换为类型“System.Int32”时出错。路径“455.hitpoints”,第 1 行,位置 1597602。---> System.InvalidCastException:Null 对象无法转换为值类型。 在 System.Convert.ChangeType(对象值,类型转换类型,IFormatProvider 提供程序) 在 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfoculture, JsonContract contract, Type targetType)
我已经尝试了许多不同的方法来做到这一点。甚至在 Entry 类的声明中将其置于生命值之上:
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
这是课程:
public class Entry
{
public Entry(int id_p, string name_p, string last_updated_p, bool incomplete_p, bool valid_p, string start_date_p, int items_p, int size_p, int hitpoints_p)
{
id = id_p;
name = name_p;
last_updated = last_updated_p;
incomplete = incomplete_p;
valid = valid_p;
start_date = start_date_p;
items = items_p;
size = size_p;
hitpoints = hitpoints_p;
}
public int id { get; set; }
public string name { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string last_updated { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public bool incomplete { get; set; }
public bool valid { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string start_date { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int items { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int current { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int hitpoints { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
}
仍在做同样的事情。有什么想法吗?
【问题讨论】:
-
Entry类是如何定义的? -
另外,可能是粘贴错误,但您的
[JsonProperty(...)]应该在它相关的属性之前,而不是之后。最后你有一个“悬”。 -
@Nenad 正确,恕我直言,用户应该使用
JsonSerializerSettings和NullValueHandling = NullValueHandling.Ignore并完全摆脱[JsonProperty...]。 -
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]不起作用的事实似乎与您的Entry类具有参数化构造函数这一事实有关。添加默认构造函数可以解决问题,请参阅dotnetfiddle.net/AwIn0U。有点奇怪,感觉像是 Json.NET 的一个错误。