3

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'. Line 1, position 31."}. I cannot change the log format.

I think I might need to parse the date string myself using a Converter. However, I cannot find any examples of JsonConverter that seem relevant. Specifically how to read the value from the reader in the ReadJson method.

Are there any simple examples that I should look at? Or am I going about this the wrong way?

Niklas
  • 5,736
  • 7
  • 35
  • 42
  • This question over at stack apps looks like it does what you need: http://stackapps.com/questions/1175/how-to-convert-unix-timestamp-to-net-datetime/1176 – ilivewithian Apr 25 '12 at 08:49
  • Thanks. Yes, I saw it before, but since the code in the ReadJson method is commented out I didn't see it as a very good example. – Niklas Apr 25 '12 at 08:55
  • Scroll down through the example, there is an uncommented version of the ReadJson method. Either way, the basic principle of the example is sound. – ilivewithian Apr 25 '12 at 09:05
  • The comma is because it's the decimal separator. I'm more interested in the general way of helping Json.net parse something. – Niklas Apr 25 '12 at 11:31

2 Answers2

5

The format on your DateTime string uses a comma for the decimal separator (,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). This would deserialise using the culture you specify rather than the default InvariantCulture.

raveturned
  • 2,637
  • 24
  • 30
  • Looks nice. However, my version of json.net (which I currently cannot upgrade for dependency reasons) doesn't have the Culture or Date* properties on JsonSerializerSettings. – Niklas Apr 25 '12 at 11:42
  • Unfortunate. :/ In that case I guess you're forced down the custom Converter route. Is [this SO entry](http://stackoverflow.com/q/8030538/608457) useful at all? – raveturned Apr 25 '12 at 12:40
-1

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 (e.g. a lot of European languages other than English). You could try changing your locale to match so that the parsing would work?

Steve
  • 8,469
  • 1
  • 26
  • 37