强制JObject在"dd-mm-yyyy"中序列化日期格式 [英] Force JObject to serialzie date in "dd-mm-yyyy" format

查看:74
本文介绍了强制JObject在"dd-mm-yyyy"中序列化日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public Guid AddJobs(JObject parametrs)
{
        dynamic jsonParameters = parametrs;
        JobViewModel job = jsonParameters.Job.ToObject<JobViewModel>();
}

以上是我的代码.我正在尝试使用上述方法反序列化此模型.问题是它不断给我例外,因为日期格式不正确,因为它不希望出现"dd-mm-yyyy".请帮我解决这个问题.

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.直接在串行器上设置格式.它将在错误的值上引发异常.

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.创建一个自定义转换器并处理错误值,没有例外:

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);

这篇关于强制JObject在"dd-mm-yyyy"中序列化日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆