Exemple #1
0
 /// <summary>
 /// 获取指定类型的所有属性元数据。
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public virtual List <SerializerPropertyMetadata> GetProperties(Type type)
 {
     return(_cache.GetOrAdd(type, k =>
     {
         return k.GetProperties()
         .Where(s => s.CanRead && !SerializerUtil.IsNoSerializable(_option, s))
         .Distinct(new SerializerUtil.PropertyEqualityComparer())
         .Select(s => new SerializerPropertyMetadata
         {
             Filter = (p, l) =>
             {
                 return !SerializerUtil.CheckLazyValueCreate(l, p.Name);
             },
             Getter = o => ReflectionCache.GetAccessor(s).GetValue(o),
             Setter = (o, v) => ReflectionCache.GetAccessor(s).SetValue(o, v),
             PropertyInfo = s,
             PropertyName = ResolvePropertyName(s),
             Formatter = s.GetCustomAttributes <TextFormatterAttribute>().FirstOrDefault()?.Formatter,
             DefaultValue = s.GetCustomAttributes <DefaultValueAttribute>().FirstOrDefault()?.Value,
             Converter = s.GetCustomAttributes <TextPropertyConverterAttribute>().FirstOrDefault()?.ConverterType.New <ITextConverter>()
         })
         .Where(s => !string.IsNullOrEmpty(s.PropertyName))
         .ToList();
     }));
 }
        private DateTime?DeserializeDateTime(string value)
        {
            if (value.Length == 0)
            {
                return(null);
            }

            return(SerializerUtil.ParseDateTime(value, null, _option.DateTimeZoneHandling));
        }
Exemple #3
0
 private IEnumerable <DataColumn> GetDataColumns(DataTable table)
 {
     foreach (DataColumn column in table.Columns)
     {
         if (!SerializerUtil.IsNoSerializable(_option, column.ColumnName))
         {
             yield return(column);
         }
     }
 }
        private object DeserializeValue(Type type)
        {
            var stype    = type.GetNonNullableType();
            var typeCode = Type.GetTypeCode(stype);

            if (typeCode == TypeCode.Object && stype != typeof(TimeSpan))
            {
                return(ParseObject(type));
            }

            if (_xmlReader.IsEmptyElement)
            {
                if (_xmlReader.NodeType == XmlNodeType.Element)
                {
                    XmlReaderHelper.ReadAndConsumeMatchingEndElement(_xmlReader);
                }

                return(type.GetDefaultValue());
            }

            bool beStartEle;

            if ((beStartEle = (_xmlReader.NodeType == XmlNodeType.Element)))
            {
                XmlReaderHelper.ReadUntilAnyTypesReached(_xmlReader, new[] { XmlNodeType.EndElement, XmlNodeType.Text, XmlNodeType.CDATA });
            }

            var value = _xmlReader.NodeType == XmlNodeType.EndElement ? string.Empty : _xmlReader.ReadContentAsString();

            if (beStartEle)
            {
                XmlReaderHelper.ReadAndConsumeMatchingEndElement(_xmlReader);
            }

            if (type.GetNonNullableType() == typeof(DateTime))
            {
                CheckNullString(value, type);
                return(SerializerUtil.ParseDateTime(value, _option.Culture, _option.DateTimeZoneHandling));
            }
            else if (type.GetNonNullableType() == typeof(TimeSpan))
            {
                if (TimeSpan.TryParse(value, out TimeSpan result))
                {
                    return(result);
                }
            }

            return(value.ToType(type));
        }
        private object DeserializeValue(Type type)
        {
            if (_jsonReader.IsNull())
            {
                if ((type.GetNonNullableType().IsValueType&& !type.IsNullableType()))
                {
                    throw new SerializationException(SR.GetString(SRKind.JsonNullableType, type));
                }

                return(null);
            }

            var stype    = type.GetNonNullableType();
            var typeCode = Type.GetTypeCode(stype);

            if (typeCode == TypeCode.Object)
            {
                return(ParseObject(type));
            }

            var value = _jsonReader.ReadValue();

            if (type.IsNullableType() && (value == null || string.IsNullOrEmpty(value.ToString())))
            {
                return(null);
            }

            switch (typeCode)
            {
            case TypeCode.DateTime:
                CheckNullString(value, type);
                return(SerializerUtil.ParseDateTime(value.ToString(), _option.Culture, _option.DateTimeZoneHandling));

            case TypeCode.String:
                return(value == null ? null : DeserializeString(value.ToString()));

            default:
                CheckNullString(value, type);
                try
                {
                    return(value.ToType(stype));
                }
                catch (Exception ex)
                {
                    throw new SerializationException(SR.GetString(SRKind.DeserializeError, value, type), ex);
                }
            }
        }
Exemple #6
0
        private void SerializeDateTime(DateTime value)
        {
            value = SerializerUtil.EnsureDateTime(value, _option.DateTimeZoneHandling);

            if (_option.DateFormatHandling == DateFormatHandling.Default)
            {
                _jsonWriter.WriteValue(string.Concat(JsonTokens.StringDelimiter, (value.Year <= 1 ? string.Empty : value.ToString(_context.SerializeInfo?.Formatter ?? "yyyy-MM-dd")), JsonTokens.StringDelimiter));
            }
            else if (_option.DateFormatHandling == DateFormatHandling.IsoDateFormat)
            {
                _jsonWriter.WriteValue(string.Concat(JsonTokens.StringDelimiter, value.GetDateTimeFormats('s')[0].ToString(_option.Culture), JsonTokens.StringDelimiter));
            }
            else if (_option.DateFormatHandling == DateFormatHandling.MicrosoftDateFormat)
            {
                var offset = TimeZoneInfo.Local.GetUtcOffset(value);
                var time   = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                var ticks  = (value.ToUniversalTime().Ticks - time.Ticks) / 10000;

                var sb = new StringBuilder();
                sb.Append("\"\\/Date(" + ticks);

                if (value.Kind == DateTimeKind.Local)
                {
                    sb.Append(offset.Ticks >= 0 ? "+" : "-");
                    var h = Math.Abs(offset.Hours);
                    var m = Math.Abs(offset.Minutes);
                    if (h < 10)
                    {
                        sb.Append(0);
                    }

                    sb.Append(h);
                    if (m < 10)
                    {
                        sb.Append(0);
                    }

                    sb.Append(m);
                }

                sb.Append(")\\/\"");
                _jsonWriter.WriteValue(sb);
            }
        }
Exemple #7
0
        /// <summary>
        /// 获取指定类型的属性访问缓存。
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private Dictionary <string, PropertyAccessor> GetAccessorCache(Type type)
        {
            return(context.SetAccessors.TryGetValue(type, () =>
            {
                return type.GetProperties()
                .Where(s => s.CanWrite && !SerializerUtil.IsNoSerializable(option, s))
                .Select(s =>
                {
                    var ele = s.GetCustomAttributes <TextSerializeElementAttribute>().FirstOrDefault();
                    //如果使用Camel命名,则名称第一位小写
                    var name = ele != null ?
                               ele.Name : (option.CamelNaming ?
                                           char.ToLower(s.Name[0]) + s.Name.Substring(1) : s.Name);

                    return new { name, p = s };
                })
                .ToDictionary(s => s.name, s => ReflectionCache.GetAccessor(s.p));
            }));
        }
Exemple #8
0
 /// <summary>
 /// 获取指定类型的属性访问缓存。
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 private List <PropertyGetAccessorCache> GetAccessorCache(Type type)
 {
     return(context.GetAccessors.TryGetValue(type, () =>
     {
         return type.GetProperties()
         .Where(s => s.CanRead && !SerializerUtil.IsNoSerializable(option, s))
         .Distinct(new SerializerUtil.PropertyEqualityComparer())
         .Select(s => new PropertyGetAccessorCache
         {
             Accessor = ReflectionCache.GetAccessor(s),
             Filter = (p, l) =>
             {
                 return !SerializerUtil.CheckLazyValueCreate(l, p.Name);
             },
             PropertyInfo = s,
             PropertyName = SerializerUtil.GetPropertyName(s)
         })
         .Where(s => !string.IsNullOrEmpty(s.PropertyName))
         .ToList();
     }));
 }
 /// <summary>
 /// 获取指定类型的属性访问缓存。
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public List <PropertyGetAccessorCache> GetAccessorCache(Type type)
 {
     return(GetAccessors.TryGetValue(type, () =>
     {
         return type.GetProperties()
         .Where(s => s.CanRead && !SerializerUtil.IsNoSerializable(Option, s))
         .Distinct(new SerializerUtil.PropertyEqualityComparer())
         .Select(s => new PropertyGetAccessorCache
         {
             Accessor = ReflectionCache.GetAccessor(s),
             Filter = (p, l) =>
             {
                 return !SerializerUtil.CheckLazyValueCreate(l, p.Name);
             },
             PropertyInfo = s,
             PropertyName = SerializerUtil.GetPropertyName(s),
             Formatter = s.GetCustomAttributes <TextFormatterAttribute>().FirstOrDefault()?.Formatter,
             DefaultValue = s.GetCustomAttributes <DefaultValueAttribute>().FirstOrDefault()?.Value,
             Converter = s.GetCustomAttributes <TextPropertyConverterAttribute>().FirstOrDefault()?.ConverterType.New <ITextConverter>()
         })
         .Where(s => !string.IsNullOrEmpty(s.PropertyName))
         .ToList();
     }));
 }