本文介绍了JObject ToObject-在“不良日期"崩溃转换次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JObject 来处理我的客户帖子.
我使用 ToObject 函数将 JObject 转换为强类型实体.

I'm using a JObject to handle my client post's.
I convert the JObject into a strong type entity using the ToObject function.

当datetime值无效时-例如 29 \ 05 \ 2014(因为没有29个月),我得到一个例外:

When the datetime value isn't valid - let's say 29\05\2014(since there aren't 29 months), I get an exception:

Could not convert string to DateTime: 29/05/2014. Path 'PurchaseDate.Value'.

我了解该异常,因此我想防止在这种情况下崩溃.

I understand the exception and I would like to prevent crashes in those kind of situations.

如何告诉JObject忽略无效的日期值?在我的特定情况下,我的实体是可为null的datetime对象,因此如果解析失败(而不是崩溃),我想保留为null.

How can I tell the JObject to ignore invalid date values? In my specific case my entity is a nullable datetime object so I would like to keep in null if the parsing fails(rather then crash).

在这种特定情况下,我说的是日期时间,但是如果有人可以给我一个更通用的答案,那就是我如何防止无效的解析\转换"失败,这是很好的,因为我所有的实体都包含可空值字段,而我不想在客户端上进行验证.

In this specific case I'm talking about a datetime, but if someone can give me a more generic answer on how I can prevent failures on "invalid parsing\conversions" that would be great, since all of my entities contain nullable fields and I don't want to handle validations on the client side.

推荐答案

我找到了解决方法-添加转换器:

I found a work around - Adding a converter:

   var js = new JsonSerializer
   {
       DateParseHandling = DateParseHandling.DateTime,
   };
   js.Converters.Add(new DateTimeConverter());

   dynamic jsonObject = new JObject();
   jsonObject.Date = "29/05/2014";
   var entty = ((JObject)jsonObject).ToObject<Entity>(js);

定义:

    public class Entity
    {
        public DateTime? Date { get; set; }
    }

    public class DateTimeConverter : DateTimeConverterBase
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            DateTime val;
            if (reader.Value != null && DateTime.TryParse(reader.Value.ToString(), out val))
            {
                return val;
            }

            return null;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue(((DateTime)value).ToString("MM/dd/yyyy"));
        }
    }

这篇关于JObject ToObject-在“不良日期"崩溃转换次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 16:48