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?

4
  • This question over at stack apps looks like it does what you need: stackapps.com/questions/1175/… Commented Apr 25, 2012 at 8: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. Commented Apr 25, 2012 at 8: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. Commented Apr 25, 2012 at 9:05
  • The comma is because it's the decimal separator. I'm more interested in the general way of helping Json.net parse something. Commented Apr 25, 2012 at 11:31

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Unfortunate. :/ In that case I guess you're forced down the custom Converter route. Is this SO entry useful at all?
-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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.