使用Newtonsoft.Json反序列化含Nullable DateTime属性的JSON时抛出JsonReaderException异常排查
问题原因与解决方案
这个问题的核心症结在于你的自定义DateTimeConverter没有正确处理可空DateTime类型(DateTime?),导致Json.NET根本没调用你的转换器,转而使用默认逻辑处理纯数字时间戳,最终抛出解析异常。
具体原因分析
你的Dto字段是DateTime?(可空值类型),但转换器的CanConvert方法只判断了objectType == typeof(DateTime)——可空类型的实际类型是Nullable<DateTime>,和DateTime不是同一个类型,所以Json.NET认为这个转换器不适用,直接跳过了它。
而默认情况下,Json.NET只识别/Date(1487710800000)/这种格式的时间戳,不支持直接解析纯数字long值到DateTime?,这就是为什么你会看到Unexpected character encountered while parsing value: 1的异常,同时调试时转换器代码根本没被命中。
修复方案
修改你的DateTimeConverter,让它同时支持DateTime和DateTime?类型:
1. 更新CanConvert方法
public override bool CanConvert(Type objectType) { // 获取可空类型的底层类型,同时处理非可空的DateTime Type underlyingType = Nullable.GetUnderlyingType(objectType); return (underlyingType != null && underlyingType == typeof(DateTime)) || objectType == typeof(DateTime); }
2. 完善ReadJson方法(处理null值)
当JSON字段为null时(比如你的deletedDate),需要直接返回null,避免强制类型转换出错:
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { try { // 处理null值,直接返回null if (reader.Value == null) { return null; } var t = (long)reader.Value; return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(t); } catch (Exception ex) { throw ex; } }
做完这两处修改后,Json.NET就会正确调用你的转换器,不管是可空还是非可空的DateTime字段,都能正常解析纯数字时间戳了。
内容的提问来源于stack exchange,提问作者serkanz
相关产品推荐
相关产品推荐

