[英]Converting to DateTime in json.net
I'm trying to deserialize the following: 我正在尝试反序列化以下内容:
{"ts":"2012-04-22 04:14:50,669", "msg":"Hello"}
into 成
public class LogEntry
{
public DateTime Ts { get; set; }
public string Msg { get; set; }
}
using 运用
var logEntry = JsonConvert.DeserializeObject<LogEntry>(line);
But get a JsonSerializationException saying "{"Error converting value \\"2012-04-22 04:14:28,478\\" to type 'System.DateTime'. 但得到一个JsonSerializationException说“{”错误转换值\\“2012-04-22 04:14:28,478 \\”键入'System.DateTime'。 Line 1, position 31."}. I cannot change the log format. 第1行,第31位。“}。我无法更改日志格式。
I think I might need to parse the date string myself using a Converter. 我想我可能需要使用Converter自己解析日期字符串。 However, I cannot find any examples of JsonConverter
that seem relevant. 但是,我找不到任何看似相关的JsonConverter
示例。 Specifically how to read the value from the reader
in the ReadJson
method. 具体来说,如何从ReadJson
方法中reader
中的ReadJson
。
Are there any simple examples that I should look at? 有什么简单的例子我应该看一下吗? Or am I going about this the wrong way? 或者我是以错误的方式来做这件事的?
The format on your DateTime string uses a comma for the decimal separator ( ,478
). DateTime字符串上的格式使用逗号作为小数分隔符( ,478
)。 You may be able to initialise a JsonSerializerSettings
object ( documented here ) with an appropriate Culture
, and then deserialise using DeserializeObject<T>(value, settings)
( documented here ). 您可以使用适当的Culture
初始化JsonSerializerSettings
对象( 此处记录 ),然后使用DeserializeObject<T>(value, settings)
进行反序列DeserializeObject<T>(value, settings)
( 此处记录 )。 This would deserialise using the culture you specify rather than the default InvariantCulture
. 这将使用您指定的文化而不是默认的InvariantCulture
反序列化。
I suspect the issue is because the value you are getting is using a comma as the decimal separator which suggests it was created in a locale that uses commas (eg a lot of European languages other than English). 我怀疑问题是因为您获得的值是使用逗号作为小数分隔符,这表示它是在使用逗号的语言环境中创建的(例如,除了英语之外的许多欧洲语言)。 You could try changing your locale to match so that the parsing would work? 您可以尝试更改您的区域设置以匹配,以便解析可以工作?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.