【发布时间】:2021-08-17 09:54:01
【问题描述】:
我一直在尝试读取 JSON 文件并将其反序列化为类对象。问题是我将类的TimeSpan? 属性作为string 存储在JSON 文件中,它没有被反序列化并保持为空。请在下面找到代码以供参考:
界面:
public interface IAirport
{
.
.
.
TimeSpan? TimeOffset { get; set; }
.
.
.
}
类:
public class Airport:IAirport{
.
.
.
private TimeSpan? _offsetTime;
public TimeSpan? OffssetTime
{
get{return _offsetTime;}
set{SetProperty<TimeSpan>(ref _offsetTime, value);}
}
.
.
.
}
这是我反序列化的方式:
private static T ConvertJsonStreamToObject<T>(StreamReader fileStream)
{
JsonSerializer serializer = new JsonSerializer();
return (T)serializer.Deserialize(fileStream, typeof(T));
}
最后是 JSON:
{
"AirportDesignation": "ZZU",
"EffectiveDate": "1901-01-01 00:00:00.0000000",
"Description": "Mzuzu",
"DescriptionShort": "Mzuzu",
"EffectiveStatus": "A",
"Country": "MWI",
"State": " ",
"LatitudeDegrees": 11,
"LatitudeMinutes": 27,
"LatitudeSeconds": 0,
"LatitudeCoordinates": "S",
"LongitudeDegrees": 34,
"LongitudeMinutes": 1,
"LongitudeSeconds": 0,
"LongitudeCoordinates": "E",
"AirportType": "A",
"TimeOffset": "00:00:00",
"IsTimeOffsetPositive": true
}
我尝试了以下方法来设置属性并使用TimeSpan.Parse() 将string 解析为TimeSpan,但它们都不起作用:
private string _timeOffset;
public TimeSpan? TimeOffset
{
get { return TimeSpan.Parse(_timeOffset); }
set { _timeOffset = value.ToString(); }
}
我没有想法可以尝试,任何帮助将不胜感激。
更新:
我尝试了@Caius Jard 的建议,得到了System.ArgumentNullException
更新属性如下:
private string _timeOffset;
[Required]
public TimeSpan? TimeOffset
{
get { return TimeSpan.Parse(_timeOffset); }
set { SetProperty<string>(ref _timeOffset, value.Value.ToString()); }
}
【问题讨论】:
-
我没办法尝试 - 有一个 TimeSpan 类型的属性,它是
JsonIgnore。有一个string类型属性,可以读取和写入时间跨度,因此 json 序列化程序将使用它来读取/写入字符串。在代码中使用时间跨度类型属性 -
.Net 属性名称似乎与 JSON 不匹配。为什么不简单地将属性指定为
public TimeSpan? TimeOffset { get; set; }?然后添加行为,最终。 -- 将 TimeSpan 设置为"00:00:00",属性应具有.TimeOffset.HasValue等于true和.TimeOffset.Value等于00:00:00。 -
另外,看起来您使用的是相当旧的 Json.Net 版本。这:
(T)serializer.Deserialize(fileStream, typeof(T));当前不存在,您必须传递从 Stream 初始化的 JsonTextReader,然后使用.Deserialize<T>版本。 -- 可能,更新你的 NuGet 包。 -
对我来说很好dotnetfiddle.net/PjoTVB 请给minimal reproducible example 一个实际的 JSON 字符串来反序列化,以及你使用的是哪个版本的 Newtonsoft