问题
When calling ToObject on JObject with a string property, transforms datetime value.
class Program
{
static void Main(string[] args)
{
var a = JObject.Parse("{\"aprop\":\"2012-12-02T23:03:31Z\"}");
var jobject = a.ToObject<A>();
Console.ReadKey();
}
}
public class A
{
public string AProp { get; set; }
}
The problem is I get my value transformed despite it being a string. The ISO8601 specific characters got skipped:

I expect no tranformations to happen and want to be able to do date validation and culture-specific creation myself. I also tried the next code without success:
var jobject = a.ToObject<A>(new JsonSerializer
{
DateParseHandling = DateParseHandling.None
});
The JObject.Parse is introduced for example's sake. In my real task I have a Web.Api action on a controller:
public HttpResponseMessage Put(JObject[] requestData)
{
var jobject = a.ToObject<A>();
return SomeCleverStaffResponse();
}
回答1:
what you want is
using Newtonsoft.Json;
class Program
{
static void Main(string[] args)
{
var temp = JsonConvert.DeserializeObject<A>("{\"aprop\":\"2012-12-02T23:03:31Z\"}");
Console.ReadKey();
}
}
as soon as you do Parse
since "2012-12-02T23:03:31Z\" is a date the parser creates a Date Object everything after that will already have the object parsed so the .ToObject
is useless as what you are doing is going from date to string and that's why you get the "12/...".
回答2:
Why do you parse it, when you don't want to have it parsed, at the first place? There's no reason for building a JObject
instance. Just deserialize the string using the JsonSerializer.Deserialize<T> method directly into an A
instance. You can then leverage all Json.NET's attributes (among other means) to control deserialization as you want.
来源:https://stackoverflow.com/questions/21554468/jobject-toobjectt-extension-method-transforms-datetime-values-stored-as-stri