我正在关注 official example使用 .NET 解析 JSON。
我创建了一个 products.json 文件:
{
"Name": "Apple",
"Expiry": new Date(1230422400000),
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}
将其读入字符串,然后反序列化。我正在尝试按如下方式解析它:
Product deserializedProduct;
string jsonObj = File.ReadAllText(@"..\..\Content\products.json");
if (jsonObj != null)
{
try
{
deserializedProduct = JsonConvert.DeserializeObject<Product>(jsonObj);
}
catch (Exception e)
{
//log exception;
}
}
我得到以下异常:
Error reading date. Unexpected token: StartConstructor. Path 'Expiry', line 3, position 24.
我知道 JSON 不允许日期对象,但为什么示例使用 new Date(1230422400000) 来表示日期对象。
请您参考如下方法:
你需要传入一个转换器。尝试这样的事情:
deserializedProduct = JsonConvert.DeserializeObject<Product>(jsonObj, new JavaScriptDateTimeConverter());
至于为什么,这可能是一个古老的例子,Json.NET 在使用更正式的方式 (IIRC) 之前使用旧的 Date 对象。但是,如果您告诉它如何处理它,它仍然可以序列化和反序列化。
