问题
public Guid AddJobs(JObject parametrs)
{
dynamic jsonParameters = parametrs;
JobViewModel job = jsonParameters.Job.ToObject<JobViewModel>();
}
Above is my code. I am trying to deserialize this model using above method. The problem is that it keeps on giving me exception that date is not in correct format as it is not expecting "dd-mm-yyyy". Please Help me out in this.
回答1:
Here's two approaches:
1.Set the format directly on the serializer. It will throw an exception on incorrect values.
var jsonSer = new JsonSerializer();
jsonSer.DateFormatString = "dd-MM-yyyy";
JobViewModel job = obj.ToObject<JobViewModel>(jsonSer);
2.Create a custom converter and handle incorrect values without exceptions:
public class CustomDateConverter : Newtonsoft.Json.Converters.DateTimeConverterBase
{
private static readonly string DateTimeFormat = "dd-MM-yyyy";
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
DateTime res; // default value of a date is 01/01/0001
// if parsing is successful that value will be changed, otherwise you get the default value and not and exception
DateTime.TryParseExact(reader.Value.ToString(), DateTimeFormat, null, DateTimeStyles.None, out res);
return res;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((DateTime)value).ToString(DateTimeFormat));
}
}
And add the convertor to your serializer:
var jsonSer = new JsonSerializer();
jsonSer.Converters.Add(new CustomDateConverter());
JobViewModel job = obj.ToObject<JobViewModel>(jsonSer);
回答2:
A couple of things to try here.
Don't know if this works, but you can try setting the DisplayFormat
attribute in the data annotations in your Model and specify the date format there.
Based on the JSON library that you are using, you can explore if it has some kind of date format conversion facility or some setting that you can do programmatically while using it.
Again not sure of this, but you can specify that field as string
and then after deserialization, convert it into datetime with required format.
Since you are using Json.Net, refer to their documentation and one of their links : Click here
Hope this helps.
来源:https://stackoverflow.com/questions/33971228/force-jobject-to-serialzie-date-in-dd-mm-yyyy-format