/// <summary> /// Deserializes the specified <see cref="PlainTextReader"/> to the specified type. /// </summary> /// <param name="reader"><see cref="PlainTextReader"/> thatcontains the <see cref="object"/> to be deserialized.</param> /// <param name="type"><see cref="Type"/> of the deserialized <see cref="object"/>.</param> /// <returns>Returns an instance of the specified <see cref="Type"/> loaded from the <see cref="PlainTextReader"/>.</returns> /// <exception cref="ArgumentNullException"/> /// <exception cref="FormatException">Occurs when a property did not have the correct format.</exception> public object Deserialize(PlainTextReader reader, Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (reader == null) { throw new ArgumentNullException(nameof(reader)); } object instance = Activator.CreateInstance(type); try { ReadValueObject readItem; while ((readItem = reader.ReadNextValue()) != null) { if (string.IsNullOrWhiteSpace(readItem.Name)) { throw new FormatException(Resources.SerializationExceptionStrings.PropertyNameEmpty); } if (string.IsNullOrWhiteSpace(readItem.Value)) { throw new FormatException( string.Format(Resources.SerializationExceptionStrings.PropertyValueEmpty, readItem.Name)); } PropertyInfo property = GetProperty(readItem.Name, type); if (property != null) { property.SetValue(instance, Decoder.DecodeUnknown(readItem.Value, property.PropertyType)); continue; } FieldInfo field = GetField(readItem.Name, type); if (field != null) { field.SetValue(instance, Decoder.DecodeUnknown(readItem.Value, field.FieldType)); continue; } UnknownElement?.Invoke(readItem); } } catch (FormatException ex) { throw new FormatException(string.Format(Resources.SerializationExceptionStrings.InvalidSettingFormat, reader.Position) + Environment.NewLine + ex.Message, ex); } return(instance); }
/// <summary> /// Deserializes the specified <see cref="PlainTextReader"/> to the specified type. /// </summary> /// <typeparam name="T">Type of the deserialized <see cref="object"/>.</typeparam> /// <param name="reader"><see cref="PlainTextReader"/> that contains the object to be deserialized.</param> /// <returns>Returns an instance of <see cref="T"/> loaded from the <see cref="PlainTextReader"/>.</returns> /// <exception cref = "ArgumentNullException"/><exception cref="FormatException">Occurs when a property did not have the correct format.</exception> public T Deserialize <T>(PlainTextReader reader) { Type target = typeof(T); return((T)Deserialize(reader, target)); }