Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not convert JToken date time string as DateTime

Trying to parse JToken which is holding datetime as string, as string. Implicitly what it is doing is considering it as DateTime, parsing and then passing back as string.

Original value is : "2015-11-23T00:00:00"

When I do arr["value"].ToString(); I get : "23/11/2015 00:00:00"

What I really want is whatever was passed i.e. the original value.

Have tried using Formatting.None, but that brings in double quotes etc.

Is there a simple way round?

like image 891
Yahya Avatar asked Nov 23 '15 15:11

Yahya


2 Answers

Use DateParseHandling to override JSON.NET's automatic attempts to DateTimeify anything that looks DateTimey.

void Main()
{
    var s = "{ \"value\" : \"2015-11-23T00:00:00\" }";

    using (var sr = new StringReader(s))
    using (var jr = new JsonTextReader(sr) { DateParseHandling = DateParseHandling.None })
    {
        var j = JToken.ReadFrom(jr);
        Console.WriteLine(j["value"].ToString()); // prints '2015-11-23T00:00:00'
    }
}
like image 123
user5090812 Avatar answered Nov 04 '22 04:11

user5090812


You can describe the class with this member declared as 'string' and use it in serialization, so that it is is stored in the original representation:

public class MyObject 
{ 
    public string date { get; set ; }
}

string json = "{ \"date\": \"2015-11-23T00:00:00\" }";
var myObj = JsonConvert.DeserializeObject<MyObject>(json);

Console.WriteLine(myObj.date);
like image 20
Yeldar Kurmangaliyev Avatar answered Nov 04 '22 04:11

Yeldar Kurmangaliyev