public static string Stringify(object value, StringifyOptions options = StringifyOptions.None) { if (value != null) { var buffer = new StringBuilder(); GetSerializer(value.GetType())(buffer, value, options); return(buffer.ToString()); } return("null"); }
/// <summary> /// Constructs a domain object from a given deserializer state. /// </summary> /// <typeparam name="T">Type of domain object to construct. Must be one of the following: /// <list type="bullet"> /// <item><description>Type implementing <see cref="ICapnpSerializable"/>. The type must must have a public parameterless constructor.</description></item> /// <item><description>A capability interface (<seealso cref="Rpc.InvalidCapabilityInterfaceException"/> for further explanation)</description></item> /// <item><description><see cref="string"/></description></item> /// <item><description>IReadOnlyList<bool>, IReadOnlyList<sbyte>, IReadOnlyList<byte></description></item> /// <item><description>IReadOnlyList<short>, IReadOnlyList<ushort>, IReadOnlyList<int></description></item> /// <item><description>IReadOnlyList<uint>, IReadOnlyList<long>, IReadOnlyList<ulong></description></item> /// <item><description>IReadOnlyList<float>, IReadOnlyList<double></description></item> /// <item><description>IReadOnlyList<T> whereby T is one of the things listed here.</description></item> /// </list> /// </typeparam> /// <param name="state">deserializer state to construct from</param> /// <returns>The domain object instance. Nullability note: The returned reference may be null if /// <paramref name="state"/> represents the nil object.</returns> /// <exception cref="ArgumentException">Cannot construct object of type <typeparamref name="T"/></exception> /// <remarks>Note that capability ownership is moved to the domain object</remarks> public static T?Create <T>(DeserializerState state) where T : class { try { return((T?)GetSerializer(typeof(T))(state)); } catch (TargetInvocationException ex) { throw new ArgumentException("Failed to construct domain object", ex); } }
static Serializer CreateArraySerializer(TypeInfo typeInfo) { Type itemType; if (typeInfo.HasElementType) { itemType = typeInfo.GetElementType(); } else if (typeInfo.IsGenericType && typeInfo.GenericTypeArguments.Length > 0) { itemType = typeInfo.GenericTypeArguments[0]; } else { itemType = null; } if (itemType != null && itemType != typeof(object) && !itemType.GetTypeInfo().IsAbstract) { var itemSerializer = GetSerializer(itemType); return(new ArrayWriteHelper((output, value, options) => { if (itemSerializer == null) // in case of recursion { itemSerializer = GetSerializer(itemType); } foreach (var item in (IEnumerable)value) { itemSerializer(output, item, options); output.Append(','); } }).Serializer); } return(new ArrayWriteHelper((output, value, options) => { foreach (var item in (IEnumerable)value) { if (item == null) { output.Append("null"); } else { GetSerializer(item.GetType())(output, item, options); } output.Append(','); } }).Serializer); }
public SerializationHelper(GetSerializer getSerializer) { _bonsaiSerializer = getSerializer(SerializeConstantFactory, DeserializeConstantFactory); _dataSerializer = (JsonDataSerializer)DataSerializer.Create(_bonsaiSerializer); _genericSerialize = _dataSerializer.GetType().GetMethod(nameof(DataSerializer.Serialize)); _genericDeserialize = _dataSerializer.GetType().GetMethod(nameof(DataSerializer.Deserialize)); }
static void WriteDynamicObject(StringBuilder output, object value, StringifyOptions options) { if (value == null) { output.Append("null"); } else { var realType = value.GetType(); if (realType != typeof(object)) { GetSerializer(realType)(output, value, options); } else { output.Append("{}"); } } }
static Serializer CreateMapSerializer(TypeInfo typeInfo) { if (typeInfo.IsGenericType && typeInfo.GenericTypeArguments.Length >= 2) { var valueType = typeInfo.GenericTypeArguments[1]; if (valueType != typeof(object) && !valueType.GetTypeInfo().IsAbstract) { var valueSerializer = GetSerializer(valueType); return(new MapWriteHelper((output, value, options) => { if (valueSerializer == null) // in case of recursion { valueSerializer = GetSerializer(valueType); } foreach (DictionaryEntry item in (IDictionary)value) { DoWriteString(output, item.Key.ToString()); output.Append(':'); valueSerializer(output, item.Value, options); output.Append(','); } }).Serializer); } } return(new MapWriteHelper((output, value, options) => { foreach (DictionaryEntry item in (IDictionary)value) { DoWriteString(output, item.Key.ToString()); output.Append(':'); if (item.Value == null) { output.Append("null"); } else { GetSerializer(item.Value.GetType())(output, item.Value, options); } output.Append(','); } }).Serializer); }
/// <summary> /// Constructs a domain object from a given deserializer state. /// </summary> /// <typeparam name="T">Type of domain object to construct. Must be one of the following: /// <list type="bullet"> /// <item><description>Type implementing <see cref="ICapnpSerializable"/>. The type must must have a public parameterless constructor.</description></item> /// <item><description>A capability interface (<seealso cref="Rpc.InvalidCapabilityInterfaceException"/> for further explanation)</description></item> /// <item><description><see cref="String"/></description></item> /// <item><description><code>IReadOnlyList{Boolean}</code></description></item> /// <item><description><code>IReadOnlyList{SByte}"</code></description></item> /// <item><description><code>IReadOnlyList{Byte}"</code></description></item> /// <item><description><code>IReadOnlyList{Int16}"</code></description></item> /// <item><description><code>IReadOnlyList{UInt16}"</code></description></item> /// <item><description><code>IReadOnlyList{Int32}"</code></description></item> /// <item><description><code>IReadOnlyList{UInt32}"</code></description></item> /// <item><description><code>IReadOnlyList{Int64}"</code></description></item> /// <item><description><code>IReadOnlyList{UInt64}"</code></description></item> /// <item><description><code>IReadOnlyList{Single}"</code></description></item> /// <item><description><code>IReadOnlyList{Double}"</code></description></item> /// <item><description><code>IReadOnlyList{T}</code> whereby T is one of the things listed here.</description></item> /// </list> /// </typeparam> /// <param name="state">deserializer state to construct from</param> /// <returns>The domain object instance. Nullability note: The returned reference will be null if (and only if) <typeparamref name="T"/> is a capability interface and /// <paramref name="state"/> represents the nil object (obtained from a null pointer). For all other types, when the state is nil, /// the method still constructs a valid but "empty" object instance (such as domain object without any properties set, empty string, empty list etc.)</returns> public static T?Create <T>(DeserializerState state) where T : class { return((T?)GetSerializer(typeof(T))(state)); }
public string Serialize(object obj) { return(GetSerializer.Serialize(obj)); }
private void AddElement(PropertyInfo property, List <Expression> expressions, ParameterExpression retVal, ParameterExpression objectVariable) { var name = GetNameFromXmlElementAttribute(property); var type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; Expression resultExpression; var isNullable = type != property.PropertyType; var valueOfNullableProperty = isNullable ? property.PropertyType.GetProperty(nameof(Nullable <int> .Value)) : null; var hasValueProperty = isNullable ? property.PropertyType.GetProperty(nameof(Nullable <int> .HasValue)) : null; Expression GetProperty(bool convertToObject) { if (isNullable) { // ReSharper disable once AssignNullToNotNullAttribute Expression propValue = Expression.Property(GetPropValue(objectVariable, property, false), valueOfNullableProperty); if (convertToObject) { propValue = Expression.Convert(propValue, typeof(object)); } return(propValue); } return(GetPropValue(objectVariable, property, convertToObject)); } var converterMethod = GetConverterMethod(property); if (converterMethod != null) { var call = converterMethod.IsStatic ? Expression.Call(converterMethod, GetProperty(false)) : Expression.Call(objectVariable, converterMethod, GetProperty(false)); resultExpression = Expression.Call(retVal, _setElementValue, AsXName(name), call); } else { if (type.IsPrimitive || type == typeof(string)) { resultExpression = Expression.Call(retVal, _setElementValue, AsXName(name), GetProperty(true)); } else if (type.IsEnum) { resultExpression = Expression.Call(retVal, _setElementValue, AsXName(name), Expression.Convert(GetProperty(false), Enum.GetUnderlyingType(type))); } else if (type == typeof(TimeSpan)) { var formatter = type.GetMethod(nameof(ToString), BindingFlags.Public | BindingFlags.Instance, null, new[] { typeof(string) }, null); // <retval>.SetAttributeValue(<name>, <property>.ToString("g")) resultExpression = Expression.Call(retVal, _setElementValue, AsXName(name), Expression.Call(GetProperty(false), formatter, Expression.Constant("g"))); } else if (type == typeof(DateTime) || type == typeof(DateTimeOffset)) { var formatter = type.GetMethod(nameof(ToString), BindingFlags.Public | BindingFlags.Instance, null, new[] { typeof(string) }, null); // <retval>.SetAttributeValue(<name>, <property>.ToString("O")) resultExpression = Expression.Call(retVal, _setElementValue, AsXName(name), Expression.Call(GetProperty(false), formatter, Expression.Constant("O"))); } else { Expression <Func <object, string, XElement> > bind = (o, s) => GetSerializer(o.GetType(), s)(o, s); var createChildTree = Expression.Invoke(bind, GetProperty(true), Expression.Constant(name)); resultExpression = Expression.Call(retVal, _add, createChildTree); } if (isNullable) { // ReSharper disable once AssignNullToNotNullAttribute resultExpression = Expression.IfThen( Expression.Property(GetPropValue(objectVariable, property, false), hasValueProperty), resultExpression); } else if (!type.IsValueType) { resultExpression = Expression.IfThen( Expression.NotEqual(GetPropValue(objectVariable, property, false), Expression.Constant(null, type)), resultExpression); } } expressions.Add(resultExpression); }