protected void SerializeDto <T>(T dto) { TestResults = new List <SerializersBenchmarkEntry>(); FixtureTestResults.Add(TestResults); this.ModelName = typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(List <>) ? typeof(T).GetGenericArguments()[0].Name : typeof(T).Name; if (!OnlyRunServiceStackSerializers) { var dtoMsXml = DataContractSerializer.Instance.Parse(dto); RecordRunResults("Microsoft DataContractSerializer", dtoMsXml, () => DataContractSerializer.Instance.Parse(dto), () => DataContractDeserializer.Instance.Parse <T>(dtoMsXml) ); var dtoMsJson = JsonDataContractSerializer.Instance.Parse(dto); RecordRunResults("Microsoft JsonDataContractSerializer", dtoMsJson, () => JsonDataContractSerializer.Instance.Parse(dto), () => JsonDataContractDeserializer.Instance.Parse <T>(dtoMsJson) ); if (this.MultipleIterations.Sum() <= 10) { //To slow to include, up to 280x slower than ProtoBuf var js = new JavaScriptSerializer(); var dtoJs = js.Serialize(dto); RecordRunResults("Microsoft JavaScriptSerializer", dtoJs, () => js.Serialize(dto), () => js.Deserialize <T>(dtoJs) ); //Can't import complex types, e.g. Lists, etc //var jayRockString = Jayrock.Json.Conversion.JsonConvert.ExportToString(dto); //RecordRunResults("JayRock JsonConvert", jayRockString, // () => Jayrock.Json.Conversion.JsonConvert.ExportToString(dto), // () => Jayrock.Json.Conversion.JsonConvert.Import(typeof(T), jayRockString) //); } var msBytes = BinaryFormatterSerializer.Instance.Serialize(dto); RecordRunResults("Microsoft BinaryFormatter", msBytes, () => BinaryFormatterSerializer.Instance.Serialize(dto), () => BinaryFormatterDeserializer.Instance.Deserialize <T>(msBytes) ); var dtoJsonNet = JsonConvert.SerializeObject(dto); RecordRunResults("NewtonSoft.Json", dtoJsonNet, () => JsonConvert.SerializeObject(dto), () => JsonConvert.DeserializeObject <T>(dtoJsonNet) ); //var dtoLitJson = JsonMapper.ToJson(dto); //RecordRunResults("LitJson", dtoJsonNet, // () => JsonMapper.ToJson(dto), // () => JsonMapper.ToObject<T>(dtoLitJson) //); var dtoProtoBuf = ProtoBufToBytes(dto); RecordRunResults("ProtoBuf.net", dtoProtoBuf, () => ProtoBufToBytes(dto), () => ProtoBufFromBytes <T>(dtoProtoBuf) ); } var dtoJsv = TypeSerializer.SerializeToString(dto); RecordRunResults("ServiceStack TypeSerializer", dtoJsv, () => TypeSerializer.SerializeToString(dto), () => TypeSerializer.DeserializeFromString <T>(dtoJsv) ); var dtoJson = ServiceStack.Text.JsonSerializer.SerializeToString(dto); RecordRunResults("ServiceStack JsonSerializer", dtoJson, () => ServiceStack.Text.JsonSerializer.SerializeToString(dto), () => ServiceStack.Text.JsonSerializer.DeserializeFromString <T>(dtoJson) ); //Propietary library, not freely available. //var dtoPlatformText = TextSerializer.SerializeToString(dto); //RecordRunResults("Platform TextSerializer", dtoPlatformText, // () => TextSerializer.SerializeToString(dto), // () => TextSerializer.DeserializeFromString<T>(dtoPlatformText) //); CalculateBestTimes(TestResults); }
public void Empty_list_string_returns_empty_List() { var convertedStringValues = TypeSerializer.DeserializeFromString <List <string> >("[]"); Assert.That(convertedStringValues, Is.EqualTo(new List <string>())); }
public static GetMemberDelegate CreateTypeConverter(Type fromType, Type toType) { if (fromType == toType) { return(null); } if (fromType == typeof(string)) { return(fromValue => TypeSerializer.DeserializeFromString((string)fromValue, toType)); } if (toType == typeof(string)) { return(o => TypeSerializer.SerializeToString(o).StripQuotes()); } var underlyingToType = Nullable.GetUnderlyingType(toType) ?? toType; var underlyingFromType = Nullable.GetUnderlyingType(fromType) ?? fromType; if (underlyingToType.IsEnum) { if (underlyingFromType.IsEnum || fromType == typeof(string)) { return(fromValue => Enum.Parse(underlyingToType, fromValue.ToString(), ignoreCase: true)); } if (underlyingFromType.IsIntegerType()) { return(fromValue => Enum.ToObject(underlyingToType, fromValue)); } } else if (underlyingFromType.IsEnum) { if (underlyingToType.IsIntegerType()) { return(fromValue => Convert.ChangeType(fromValue, underlyingToType, null)); } } else if (typeof(IEnumerable).IsAssignableFrom(fromType)) { return(fromValue => { var listResult = TranslateListWithElements.TryTranslateCollections( fromType, underlyingToType, fromValue); return listResult ?? fromValue; }); } else if (underlyingToType.IsValueType) { return(fromValue => AutoMappingUtils.ChangeValueType(fromValue, underlyingToType)); } else { return(fromValue => { if (fromValue == null) { return fromValue; } var toValue = toType.CreateInstance(); toValue.PopulateWith(fromValue); return toValue; }); } return(null); }
public static T ToOrDefaultValue <T>(this string value) { return(String.IsNullOrEmpty(value) ? default(T) : TypeSerializer.DeserializeFromString <T>(value)); }
public static T FromJsv <T>(this string jsv) { return(TypeSerializer.DeserializeFromString <T>(jsv)); }
public static T To <T>(this string value, T defaultValue) { return(value.IsNullOrEmpty() ? defaultValue : TypeSerializer.DeserializeFromString <T>(value)); }
public void Can_serializer_UserPublicView() { var dto = TypeSerializer.DeserializeFromString <UserPublicView>(UserViewString); Serialize(dto); }
public T Deserialize <T>(string input) { return(TypeSerializer.DeserializeFromString <T>(input)); }
public static Message <T> ToMessage <T>(this byte[] bytes) { var messageText = ToString(bytes); return(TypeSerializer.DeserializeFromString <Message <T> >(messageText)); }
public static ReleaseChangeSet Deserialize(string changeSetString) { return(TypeSerializer.DeserializeFromString <ReleaseChangeSet>(changeSetString)); }
public object Deserialize(Type graphType, string serializedValue) { return(TypeSerializer.DeserializeFromString(serializedValue, graphType)); }
public object Deserialize(Type type, string data) { return(TypeSerializer.DeserializeFromString(data, type)); }
public T Deserialize <T>(string data) where T : class { return(TypeSerializer.DeserializeFromString <T>(data)); }
public void Populate(object to, object from, Func <PropertyInfo, bool> propertyInfoPredicate, Func <object, bool> valuePredicate) { foreach (var propertyEntry in PropertyInfoMap) { var fromPropertyInfo = propertyEntry.Key; var toPropertyInfo = propertyEntry.Value; if (propertyInfoPredicate != null) { if (!propertyInfoPredicate(fromPropertyInfo)) { continue; } } try { var getterFn = PropertyGetters.GetOrAdd(fromPropertyInfo.Name, fromPropertyInfo.GetPropertyGetterFn()); var fromValue = getterFn(from); if (valuePredicate != null) { if (!valuePredicate(fromValue)) { continue; } } if (fromPropertyInfo.PropertyType != toPropertyInfo.PropertyType) { if (fromPropertyInfo.PropertyType == typeof(string)) { fromValue = TypeSerializer.DeserializeFromString((string)fromValue, toPropertyInfo.PropertyType); } else if (toPropertyInfo.PropertyType == typeof(string)) { fromValue = TypeSerializer.SerializeToString(fromValue); } else if (toPropertyInfo.PropertyType.IsGenericType && toPropertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>)) { Type genericArg = toPropertyInfo.PropertyType.GetGenericArguments()[0]; if (genericArg.IsEnum) { fromValue = Enum.ToObject(genericArg, fromValue); } } else { var listResult = TranslateListWithElements.TryTranslateToGenericICollection( fromPropertyInfo.PropertyType, toPropertyInfo.PropertyType, fromValue); if (listResult != null) { fromValue = listResult; } } } var setterFn = PropertySetters.GetOrAdd(toPropertyInfo.Name, toPropertyInfo.GetPropertySetterFn()); setterFn(to, fromValue); } catch (Exception ex) { Log.Warn(string.Format("Error trying to set properties {0}.{1} > {2}.{3}", FromType.FullName, fromPropertyInfo.Name, ToType.FullName, toPropertyInfo.Name), ex); } } foreach (var fieldEntry in FieldInfoMap) { var fromFieldInfo = fieldEntry.Key; var toFieldInfo = fieldEntry.Value; try { var fromValue = fromFieldInfo.GetValue(from); toFieldInfo.SetValue(to, fromValue); } catch (Exception ex) { Log.Warn(string.Format("Error trying to set fields {0}.{1} > {2}.{3}", FromType.FullName, fromFieldInfo.Name, ToType.FullName, toFieldInfo.Name), ex); } } }
public object DeserializeFromString(string serializedText, Type type) { return(TypeSerializer.DeserializeFromString(serializedText, type)); }
public void Populate(object to, object from, Func <PropertyInfo, bool> propertyInfoPredicate, Func <object, Type, bool> valuePredicate) { foreach (var assignmentEntry in AssignmentMemberMap) { var assignmentMember = assignmentEntry.Value; var fromMember = assignmentEntry.Value.From; var toMember = assignmentEntry.Value.To; if (fromMember.PropertyInfo != null && propertyInfoPredicate != null) { if (!propertyInfoPredicate(fromMember.PropertyInfo)) { continue; } } try { var fromValue = assignmentMember.GetValueFn(from); if (valuePredicate != null) { if (!valuePredicate(fromValue, fromMember.PropertyInfo.PropertyType)) { continue; } } if (fromMember.Type != toMember.Type) { if (fromMember.Type == typeof(string)) { fromValue = TypeSerializer.DeserializeFromString((string)fromValue, toMember.Type); } else if (toMember.Type == typeof(string)) { fromValue = TypeSerializer.SerializeToString(fromValue); } else if (toMember.Type.IsGeneric() && toMember.Type.GenericTypeDefinition() == typeof(Nullable <>)) { Type genericArg = toMember.Type.GenericTypeArguments()[0]; if (genericArg.IsEnum()) { fromValue = Enum.ToObject(genericArg, fromValue); } } else { var listResult = TranslateListWithElements.TryTranslateToGenericICollection( fromMember.Type, toMember.Type, fromValue); if (listResult != null) { fromValue = listResult; } } } var setterFn = assignmentMember.SetValueFn; setterFn(to, fromValue); } catch (Exception ex) { Tracer.Instance.WriteWarning("Error trying to set properties {0}.{1} > {2}.{3}:\n{4}", FromType.FullName, fromMember.Type.Name, ToType.FullName, toMember.Type.Name, ex); } } }
public static PropertyGetterDelegate CreateTypeConverter(Type fromType, Type toType) { if (fromType == toType) { return(null); } if (fromType == typeof(string)) { return(fromValue => TypeSerializer.DeserializeFromString((string)fromValue, toType)); } if (toType == typeof(string)) { return(TypeSerializer.SerializeToString); } if (toType.IsEnum() || fromType.IsEnum()) { if (toType.IsEnum() && fromType.IsEnum()) { return(fromValue => Enum.Parse(toType, fromValue.ToString(), ignoreCase: true)); } if (toType.IsNullableType()) { var genericArg = toType.GenericTypeArguments()[0]; if (genericArg.IsEnum()) { return(fromValue => Enum.ToObject(genericArg, fromValue)); } } else if (toType.IsIntegerType()) { if (fromType.IsNullableType()) { var genericArg = fromType.GenericTypeArguments()[0]; if (genericArg.IsEnum()) { return(fromValue => Enum.ToObject(genericArg, fromValue)); } } return(fromValue => Enum.ToObject(fromType, fromValue)); } } else if (toType.IsNullableType()) { var toTypeBaseType = toType.GenericTypeArguments()[0]; if (toTypeBaseType.IsEnum()) { if (fromType.IsEnum() || (fromType.IsNullableType() && fromType.GenericTypeArguments()[0].IsEnum())) { return(fromValue => Enum.ToObject(toTypeBaseType, fromValue)); } } return(null); } else if (typeof(IEnumerable).IsAssignableFromType(fromType)) { return(fromValue => { var listResult = TranslateListWithElements.TryTranslateCollections( fromType, toType, fromValue); return listResult ?? fromValue; }); } else if (toType.IsValueType()) { return(fromValue => Convert.ChangeType(fromValue, toType, provider: null)); } else { return(fromValue => { if (fromValue == null) { return fromValue; } var toValue = toType.CreateInstance(); toValue.PopulateWith(fromValue); return toValue; }); } return(null); }
public override object Deserialize(string serialized) { return(TypeSerializer.DeserializeFromString(serialized, _primaryType)); }
public void Can_Deserialize_text() { var dtoString = "[{Id:1,Urn:urn:post:3a944f18-920c-498a-832d-cf38fed3d0d7/1,UserId:3a944f18920c498a832dcf38fed3d0d7,DateAdded:2010-02-17T12:04:45.2845615Z,DateModified:2010-02-17T12:04:45.2845615Z,OriginUserId:3a944f18920c498a832dcf38fed3d0d7,OriginUserName:testuser1,SourceUserId:3a944f18920c498a832dcf38fed3d0d7,SourceUserName:testuser1,SubjectUrn:urn:track:1,ContentUrn:urn:track:1,TrackUrns:[],CaptionUserId:3a944f18920c498a832dcf38fed3d0d7,CaptionSourceName:testuser1,PostType:Content}]"; var fromString = TypeSerializer.DeserializeFromString <List <FlowPostTransient> >(dtoString); }
public void DateTimeKind_Does_Not_Change_With_SkipDateTimeConversion_true() { JsConfig.DateHandler = DateHandler.ISO8601; JsConfig.SkipDateTimeConversion = true; string serilizedResult; TestObject deserilizedResult; var testObject = new TestObject { Date = new DateTime(2013, 1, 1, 0, 0, 1, DateTimeKind.Utc) }; serilizedResult = TypeSerializer.SerializeToString <TestObject>(testObject); deserilizedResult = TypeSerializer.DeserializeFromString <TestObject>(serilizedResult); Assert.AreEqual(deserilizedResult.Date, testObject.Date); Assert.AreEqual(DateTimeKind.Utc, deserilizedResult.Date.Kind); using (JsConfig.With(skipDateTimeConversion: false)) { Assert.AreEqual(DateTimeKind.Local, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind); } testObject = new TestObject { Date = new DateTime(2013, 1, 1, 0, 0, 0, DateTimeKind.Utc) }; serilizedResult = TypeSerializer.SerializeToString <TestObject>(testObject); deserilizedResult = TypeSerializer.DeserializeFromString <TestObject>(serilizedResult); Assert.AreEqual(deserilizedResult.Date, testObject.Date); Assert.AreEqual(DateTimeKind.Utc, deserilizedResult.Date.Kind); using (JsConfig.With(skipDateTimeConversion: false)) { Assert.AreEqual(DateTimeKind.Local, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind); } using (JsConfig.With(alwaysUseUtc: true, skipDateTimeConversion: false)) //It will work now { Assert.AreEqual(DateTimeKind.Utc, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind); } //make sure it still keeps local local testObject = new TestObject { Date = new DateTime(2013, 1, 2, 0, 2, 0, DateTimeKind.Local) }; serilizedResult = TypeSerializer.SerializeToString <TestObject>(testObject); deserilizedResult = TypeSerializer.DeserializeFromString <TestObject>(serilizedResult); Assert.AreEqual(deserilizedResult.Date, testObject.Date); Assert.AreEqual(DateTimeKind.Local, deserilizedResult.Date.Kind); using (JsConfig.With(alwaysUseUtc: true)) { Assert.AreEqual(DateTimeKind.Local, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind); } using (JsConfig.With(alwaysUseUtc: true, skipDateTimeConversion: false)) { Assert.AreEqual(DateTimeKind.Utc, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind); } testObject = new TestObject { Date = new DateTime(2013, 1, 2, 0, 2, 0, DateTimeKind.Unspecified) }; serilizedResult = TypeSerializer.SerializeToString <TestObject>(testObject); deserilizedResult = TypeSerializer.DeserializeFromString <TestObject>(serilizedResult); Assert.AreEqual(deserilizedResult.Date, testObject.Date); Assert.AreEqual(DateTimeKind.Unspecified, deserilizedResult.Date.Kind); using (JsConfig.With(alwaysUseUtc: true)) { Assert.AreEqual(DateTimeKind.Unspecified, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind); } using (JsConfig.With(alwaysUseUtc: true, skipDateTimeConversion: false)) { Assert.AreEqual(DateTimeKind.Utc, TypeSerializer.DeserializeFromString <TestObject>(TypeSerializer.SerializeToString <TestObject>(testObject)).Date.Kind); } using (JsConfig.With(skipDateTimeConversion: false)) { serilizedResult = TypeSerializer.SerializeToString <TestObject>(testObject); deserilizedResult = TypeSerializer.DeserializeFromString <TestObject>(serilizedResult); Assert.AreEqual(DateTimeKind.Local, deserilizedResult.Date.Kind); } }
public static T To <T>(this string value) { return(TypeSerializer.DeserializeFromString <T>(value)); }
public void TestSqlServerDateTime() { var result = TypeSerializer.DeserializeFromString <DateTime>("2010-06-01 21:52:59.280"); Assert.That(result, Is.Not.Null); }
public static object To(this string value, Type type) { return(TypeSerializer.DeserializeFromString(value, type)); }
public void JsvSerializerHonorsIgnoreMemberAttribute() { DoIgnoreMemberTest(r => TypeSerializer.SerializeToString(r), s => TypeSerializer.DeserializeFromString <RequestWithIgnoredMembers>(s)); }
public void Can_convert_to_nullable_enum_with_null_value() { var enumValue = TypeSerializer.DeserializeFromString <TestEnum?>(null); Assert.That(enumValue, Is.Null); }
public T GetArgumentValue <T>(int index) { return(TypeSerializer.DeserializeFromString <T>(this.Arguments[index])); }
public static object ChangeValueType(object from, Type toType) { var fromType = from.GetType(); if (!fromType.IsEnum && !toType.IsEnum) { if (toType == typeof(char) && from is string s) { return(s.Length > 0 ? (object)s[0] : null); } if (toType == typeof(string) && from is char c) { return(c.ToString()); } if (toType == typeof(TimeSpan) && from is long ticks) { return(new TimeSpan(ticks)); } if (toType == typeof(long) && from is TimeSpan time) { return(time.Ticks); } var destNumberType = DynamicNumber.GetNumber(toType); var value = destNumberType?.ConvertFrom(from); if (value != null) { if (toType == typeof(char)) { return(value.ToString()[0]); } return(value); } if (toType == typeof(string)) { var srcNumberType = DynamicNumber.GetNumber(from.GetType()); if (srcNumberType != null) { return(srcNumberType.ToString(@from)); } } } if (from is string strValue) { return(TypeSerializer.DeserializeFromString(strValue, toType)); } if (toType == typeof(string)) { return(from.ToJsv()); } if (toType.HasInterface(typeof(IConvertible))) { return(Convert.ChangeType(from, toType, provider: null)); } return(TypeSerializer.DeserializeFromString(from.ToJsv(), toType)); }
public To DeserializeFromString <To>(string serializedText) { return(TypeSerializer.DeserializeFromString <To>(serializedText)); }
public void Empty_map_string_returns_empty_List() { var convertedStringValues = TypeSerializer.DeserializeFromString <Dictionary <string, string> >("{}"); Assert.That(convertedStringValues, Is.EqualTo(new Dictionary <string, string>())); }
public void Populate(object to, object from, Func <PropertyInfo, bool> propertyInfoPredicate, Func <object, bool> valuePredicate) { foreach (var propertyEntry in PropertyInfoMap) { var fromPropertyInfo = propertyEntry.Key; var toPropertyInfo = propertyEntry.Value; if (propertyInfoPredicate != null) { if (!propertyInfoPredicate(fromPropertyInfo)) { continue; } } try { var fromValue = fromPropertyInfo.GetValue(from, new object[] { }); if (valuePredicate != null) { if (!valuePredicate(fromValue)) { continue; } } if (fromPropertyInfo.PropertyType != toPropertyInfo.PropertyType) { if (fromPropertyInfo.PropertyType == typeof(string)) { fromValue = TypeSerializer.DeserializeFromString((string)fromValue, toPropertyInfo.PropertyType); } else if (toPropertyInfo.PropertyType == typeof(string)) { fromValue = TypeSerializer.SerializeToString(fromValue); } else { var listResult = TranslateListWithElements.TryTranslateToGenericICollection( fromPropertyInfo.PropertyType, toPropertyInfo.PropertyType, fromValue); if (listResult != null) { fromValue = listResult; } } } var toSetMetodInfo = toPropertyInfo.GetSetMethod(); toSetMetodInfo.Invoke(to, new[] { fromValue }); } catch (Exception ex) { Log.Error(string.Format("Error trying to set properties {0}.{1} > {2}.{3}", FromType.FullName, fromPropertyInfo.Name, ToType.FullName, toPropertyInfo.Name), ex); } } foreach (var fieldEntry in FieldInfoMap) { var fromFieldInfo = fieldEntry.Key; var toFieldInfo = fieldEntry.Value; try { var fromValue = fromFieldInfo.GetValue(from); toFieldInfo.SetValue(to, fromValue); } catch (Exception ex) { Log.Error(string.Format("Error trying to set fields {0}.{1} > {2}.{3}", FromType.FullName, fromFieldInfo.Name, ToType.FullName, toFieldInfo.Name), ex); } } }