简体   繁体   中英

Newtonsoft.Json custom object collection deserializer

Is there any way to specify custom deserialization for collection of objects but only for dates?

Here is what do i mean:

Let's say I have collection of objects - it could be any object and json deserialized them pretty good. Everything is fine instead of dates.

public List<object> Values { get; set; }

I don't want to set any properties globally - but only for this property. If there is a DateTime in collection of Values - I want to deserialize it in my own way (eg without time).

What can you suggest me?

Globally i use this settings:

var settings = new Newtonsoft.Json.JsonSerializerSettings()
{
   DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, 
   DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc                     
};

Use Case:

For instance I have such structure:

{
  "Intance": 1,
  "Values": [
    "Ivan",
    "488-555-1212",
    "United States",
    {
      "ShortDesc": "NY",
      "LongDesc": "New York"
    },
    "1985-05-01T00:00:00-05:00"
  ],
  "LastUpdated": "2017-02-06T22:11:34-05:00"
}

Let's say - it is birthdate -

"1985-05-01T00:00:00-05:00".

Eg Web Services time zone - Eastern Time: -5 .

My time zone is Central Time (US): -6 .

In this case I will get: 1985-04-30 - It is day behind. It is right, but I don't need such behavior, because it is my birthday and it shouldn't take into account time zones.

LastUpdated property will deserialize correctly.

I was able to make it work by adding custom contract resolver and custom attribute. So when resolver sees that attribute it deserializes date as expected.

[AttributeUsage(AttributeTargets.Property)]
public class IgnoreTimeZoneAttribute : Attribute
{
}

public class IgnoreTimeZonePropertyResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        IList<JsonProperty> props = base.CreateProperties(type, memberSerialization);

        foreach (JsonProperty prop in props)
        {
            PropertyInfo pi = type.GetProperty(prop.UnderlyingName);

            if (pi != null && pi.GetCustomAttribute(typeof(IgnoreTimeZoneAttribute), true) != null)
            {
                prop.ValueProvider = new IgnoreTimeZoneValueProvider(pi);
            }
        }

        return props;
    }

    public class IgnoreTimeZoneValueProvider : IValueProvider
    {
        private PropertyInfo _targetProperty;

        public IgnoreTimeZoneValueProvider(PropertyInfo targetProperty)
        {
            this._targetProperty = targetProperty;
        }

        // GetValue is called by Json.Net during serialization.
        public object GetValue(object target)
        {
            return _targetProperty.GetValue(target);
        }

        // SetValue gets called by Json.Net during deserialization.
        // The value parameter has the value/values read from the JSON;
        // target is the object on which to set the value/values without TimeZone info.
        public void SetValue(object target, object value)
        {
            var newValue = value;

            if (typeof(IList).IsAssignableFrom(_targetProperty.PropertyType))
            {
                IList<object> values = value as IList<object>;

                if (values != null)
                {
                    for (int i = 0; i < values.Count - 1; i++)
                    {
                        var curValue = values[i];
                        if (curValue != null && curValue.GetType() == typeof(DateTime))
                        {
                            DateTimeOffset dateTime = new DateTimeOffset((DateTime)curValue);
                            values[i] = dateTime.UtcDateTime.Date;
                        }
                    }
                }
            }

            _targetProperty.SetValue(target, newValue);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM