Пример #1
0
        /// <inheritdoc/>
        public object FromJson(Type type, string json, ISerializationOptions options = null)
        {
            var serializer = CreateSerializerForDeserialization(options);

            using (var textReader = new StringReader(json))
            {
                using (var reader = new JsonTextReader(textReader))
                {
                    object instance;

                    if (type.IsConcept())
                    {
                        var genericArgumentType = type.GetConceptValueType();
                        var value = serializer.Deserialize(reader, genericArgumentType);
                        return(ConceptFactory.CreateConceptInstance(type, value));
                    }

                    if (type.GetTypeInfo().IsValueType ||
                        type.HasInterface <IEnumerable>())
                    {
                        instance = serializer.Deserialize(reader, type);
                    }
                    else
                    {
                        IEnumerable <string> propertiesMatched;
                        instance = CreateInstanceOf(type, json, out propertiesMatched);

                        DeserializeRemaindingProperties(type, serializer, reader, instance, propertiesMatched);
                    }
                    return(instance);
                }
            }
        }
Пример #2
0
        public object FromJson(Type type, string json, ISerializationOptions options = null)
        {
            var serializer = CreateSerializerForDeserialization(options);

            using (var textReader = new StringReader(json))
            {
                using (var reader = new JsonTextReader(textReader))
                {
                    object instance;

                    if (type.IsConcept())
                    {
                        var genericArgumentType = type.GetTypeInfo().BaseType.GetTypeInfo().GetGenericArguments()[0];
                        var value = serializer.Deserialize(reader, genericArgumentType);
                        return(ConceptFactory.CreateConceptInstance(type, value));
                    }

                    if (type.GetTypeInfo().IsValueType ||
                        type.HasInterface <IEnumerable>())
                    {
                        instance = serializer.Deserialize(reader, type);
                    }
                    else
                    {
                        instance = CreateInstanceOf(type, json);
                        serializer.Populate(reader, instance);
                    }
                    return(instance);
                }
            }
        }
Пример #3
0
 /// <summary>
 /// Serializes the given data object as a string.
 /// </summary>
 public static string Serialize <T>(this ISerializer serializer, T data, ISerializationOptions options = null)
 {
     using (var writer = new StringWriter())
     {
         serializer.Serialize(writer, data, options);
         return(writer.ToString());
     }
 }
Пример #4
0
 private JsonSerializer RetrieveSerializer(ISerializationOptions options, bool includeTypeNames)
 {
     if (includeTypeNames)
     {
         return(_cacheAutoTypeName.GetOrAdd(options, _ => CreateSerializer(options, TypeNameHandling.Auto)));
     }
     return(_cacheNoneTypeName.GetOrAdd(options, _ => CreateSerializer(options, TypeNameHandling.None)));
 }
Пример #5
0
        JsonSerializer CreateSerializerForSerialization(ISerializationOptions options)
        {
            if (options == null)
            {
                options = SerializationOptions.Default;
            }

            return(RetrieveSerializer(options, options.Flags.HasFlag(SerializationOptionsFlags.IncludeTypeNames)));
        }
Пример #6
0
 /// <inheritdoc/>
 public string ToJson(object instance, ISerializationOptions options = null)
 {
     using (var stringWriter = new StringWriter())
     {
         var serializer = CreateSerializerForSerialization(options);
         serializer.Serialize(stringWriter, instance);
         var serialized = stringWriter.ToString();
         return(serialized);
     }
 }
Пример #7
0
        public void Serialize(TextWriter writer, object graph, ISerializationOptions options = null)
        {
            var jsonWriter = new JsonTextWriter(writer);
            var serializer = CreateSerializerForSerialization(options);

            serializer.Serialize(jsonWriter, graph);

            // We don't close the stream as it's owned by the message.
            writer.Flush();
        }
Пример #8
0
 JsonSerializer RetrieveSerializer(ISerializationOptions options)
 {
     if (options.Flags.HasFlag(SerializationOptionsFlags.IncludeTypeNames))
     {
         return(_cacheAutoTypeName.GetOrAdd(options, _ => CreateSerializer(options, TypeNameHandling.Auto)));
     }
     else
     {
         return(_cacheNoneTypeName.GetOrAdd(options, _ => CreateSerializer(options, TypeNameHandling.None)));
     }
 }
Пример #9
0
        /// <inheritdoc/>
        public void FromJson(object instance, string json, ISerializationOptions options = null)
        {
            var serializer = CreateSerializerForDeserialization(options);

            using (var textReader = new StringReader(json))
            {
                using (var reader = new JsonTextReader(textReader))
                {
                    serializer.Populate(reader, instance);
                }
            }
        }
Пример #10
0
        /// <inheritdoc/>
        public Stream ToJsonStream(object instance, ISerializationOptions options = null)
        {
            var serialized = ToJson(instance, options);

            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);

            writer.Write(serialized);
            writer.Flush();
            stream.Position = 0;

            return(stream);
        }
Пример #11
0
        private JsonSerializer CreateSerializer(ISerializationOptions options, TypeNameHandling typeNameHandling)
        {
            var contractResolver = new SerializerContractResolver(_serviceProvider, options);

            var serializer = new JsonSerializer
            {
                TypeNameHandling = typeNameHandling,
                ContractResolver = contractResolver,
            };

            serializer.Converters.Add(new ExceptionConverter());

            return(serializer);
        }
Пример #12
0
        public object Deserialize(TextReader reader, Type targetType, ISerializationOptions options = null)
        {
            var jsonReader = new JsonTextReader(reader);

            try
            {
                var serializer = CreateSerializerForDeserialization(options);
                return(serializer.Deserialize(jsonReader, targetType));
            }
            catch (JsonSerializationException e)
            {
                throw new SerializationException(e.Message, e);
            }
        }
Пример #13
0
        public object Deserialize(TextReader reader, ISerializationOptions options = null)
        {
            var jsonReader = new JsonTextReader(reader);

            try
            {
                var serializer = CreateSerializerForDeserialization(options);
                return(serializer.Deserialize(jsonReader));
            }
            catch (JsonSerializationException e)
            {
                // Wrap in a standard .NET exception.
                throw new SerializationException(e.Message, e);
            }
        }
Пример #14
0
        JsonSerializer CreateSerializer(ISerializationOptions options, TypeNameHandling typeNameHandling)
        {
            var contractResolver = new SerializerContractResolver(_container, options);

            var serializer = new JsonSerializer
            {
                TypeNameHandling = typeNameHandling,
                ContractResolver = contractResolver,
            };

            serializer.Converters.Add(new MethodInfoConverter());
            serializer.Converters.Add(new ConceptConverter());
            serializer.Converters.Add(new ConceptDictionaryConverter());
            serializer.Converters.Add(new EventSourceVersionConverter());

            return(serializer);
        }
Пример #15
0
        /// <inheritdoc/>
        public object FromJson(Type type, string json, ISerializationOptions options = null)
        {
            var serializer = CreateSerializerForDeserialization(options);

            using (var textReader = new StringReader(json))
            {
                using (var reader = new JsonTextReader(textReader))
                {
                    object instance;

                    if (type.HasDefaultConstructor())
                    {
                        try
                        {
                            var value = serializer.Deserialize(reader, type);
                            if (value == null || value.GetType() != type)
                            {
                                var converter = serializer.Converters.SingleOrDefault(c => c.CanConvert(type) && c.CanRead);
                                if (converter != null)
                                {
                                    return(converter.ReadJson(reader, type, null, serializer));
                                }
                            }
                            else
                            {
                                return(value);
                            }
                        } catch {}
                    }

                    if (type.GetTypeInfo().IsValueType ||
                        type.HasInterface <IEnumerable>())
                    {
                        instance = serializer.Deserialize(reader, type);
                    }
                    else
                    {
                        IEnumerable <string> propertiesMatched;
                        instance = CreateInstanceOf(type, json, out propertiesMatched);

                        DeserializeRemaindingProperties(type, serializer, reader, instance, propertiesMatched);
                    }
                    return(instance);
                }
            }
        }
Пример #16
0
        JsonSerializer CreateSerializer(ISerializationOptions options, TypeNameHandling typeNameHandling)
        {
            var contractResolver = new SerializerContractResolver(_container, options);

            var serializer = new JsonSerializer
            {
                TypeNameHandling = typeNameHandling,
                ContractResolver = contractResolver,
            };

            serializer.Converters.Add(new ApplicationResourceIdentifierJsonConverter(_applicationResourceIdentifierConverter));
            serializer.Converters.Add(new ExceptionConverter());
            serializer.Converters.Add(new ConceptConverter());
            serializer.Converters.Add(new ConceptDictionaryConverter());
            serializer.Converters.Add(new EventSourceVersionConverter());
            serializer.Converters.Add(new CamelCaseToPascalCaseExpandoObjectConverter());

            return(serializer);
        }
Пример #17
0
 JsonSerializer RetrieveSerializer(ISerializationOptions options, bool ignoreReadOnlyProperties = false)
 {
     if (options.Flags.HasFlag(SerializationOptionsFlags.IncludeTypeNames))
     {
         if (ignoreReadOnlyProperties)
         {
             return(_cacheAutoTypeNameReadOnly.GetOrAdd(options, _ => CreateSerializer(options, TypeNameHandling.Auto, ignoreReadOnlyProperties)));
         }
         return(_cacheAutoTypeName.GetOrAdd(options, _ => CreateSerializer(options, TypeNameHandling.Auto, ignoreReadOnlyProperties)));
     }
     else
     {
         if (ignoreReadOnlyProperties)
         {
             return(_cacheNoneTypeNameReadOnly.GetOrAdd(options, _ => CreateSerializer(options, TypeNameHandling.None, ignoreReadOnlyProperties)));
         }
         return(_cacheNoneTypeName.GetOrAdd(options, _ => CreateSerializer(options, TypeNameHandling.None, ignoreReadOnlyProperties)));
     }
 }
Пример #18
0
        JsonSerializer CreateSerializer(ISerializationOptions options, TypeNameHandling typeNameHandling, bool ignoreReadOnlyProperties = false)
        {
            var contractResolver = new SerializerContractResolver(options, ignoreReadOnlyProperties);

            var serializer = new JsonSerializer
            {
                TypeNameHandling = typeNameHandling,
                ContractResolver = contractResolver,
            };

            if (!options.IgnoreDiscoveredConverters)
            {
                _converters.ForEach(serializer.Converters.Add);
            }
            SetSerializerForConvertersRequiringIt(options.Converters);
            options.Converters.ForEach(serializer.Converters.Add);
            options.Callback(serializer);

            return(serializer);
        }
Пример #19
0
 /// <summary>
 /// Deserializes the specified string into an object of type <typeparamref name="T"/>.
 /// </summary>
 /// <exception cref="System.InvalidCastException">The deserialized object is not of type <typeparamref name="T"/>.</exception>
 public static T Deserialize <T>(this ISerializer serializer, string serialized, ISerializationOptions options = null)
 {
     using (var reader = new StringReader(serialized))
     {
         return((T)serializer.Deserialize(reader, options));
     }
 }
Пример #20
0
 JsonSerializer CreateSerializerForSerialization(ISerializationOptions options = null)
 {
     return(RetrieveSerializer(options ?? SerializationOptions.Default, false));
 }
Пример #21
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="serializer"></param>
 /// <param name="instance"></param>
 /// <param name="options"></param>
 /// <returns></returns>
 public static byte[] ToJsonBytes(this ISerializer serializer, object instance, ISerializationOptions options = null)
 {
     return(Encoding.UTF8.GetBytes(serializer.ToJson(instance, options)));
 }
Пример #22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="serializer"></param>
        /// <param name="data"></param>
        /// <param name="options"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T FromJsonBytes <T>(this ISerializer serializer, byte[] data, ISerializationOptions options = null)
        {
            var json = Encoding.UTF8.GetString(data);

            return(serializer.FromJson <T>(json, options));
        }
Пример #23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="serializer"></param>
        /// <param name="data"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static PropertyBag PropertyBagFromJsonBytes(this ISerializer serializer, byte[] data, ISerializationOptions options = null)
        {
            var json = Encoding.UTF8.GetString(data);
            var dict = serializer.GetKeyValuesFromJson(json);

            return(new PropertyBag(new NullFreeDictionary <string, object>(dict)));
        }
Пример #24
0
        /// <summary>
        /// Writes a response with the given result and status code.
        /// </summary>
        /// <typeparam name="T">The type of the result.</typeparam>
        /// <param name="context">The <see cref="HttpContext" />.</param>
        /// <param name="statusCode">The HTTP status code.</param>
        /// <param name="result">The result.</param>
        /// <param name="options">Optional <see cref="ISerializationOptions"/> to configure the JSON serialization.</param>
        /// <returns>A task that represents the asynchronous operation.</returns>
        public static Task RespondWithStatusCodeAndResult <T>(this HttpContext context, int statusCode, T result, ISerializationOptions options = null)
        {
            var serializer = context.RequestServices.GetRequiredService <ISerializer>();

            context.Response.StatusCode  = statusCode;
            context.Response.ContentType = "application/json";
            return(context.Response.WriteAsync(serializer.ToJson(result, options)));
        }
Пример #25
0
 /// <summary>
 /// Initializes a new instance of <see cref="SerializerContractResolver"/>
 /// </summary>
 /// <param name="serviceProvider">A <see cref="IServiceProvider"/> to use for creating instances of types</param>
 /// <param name="options"><see cref="ISerializationOptions"/> to use during resolving</param>
 public SerializerContractResolver(IServiceProvider serviceProvider, ISerializationOptions options)
 {
     _serviceProvider = serviceProvider;
     _options         = options;
 }
Пример #26
0
 /// <inheritdoc/>
 public T FromJson <T>(string json, ISerializationOptions options = null)
 {
     return((T)FromJson(typeof(T), json, options));
 }
Пример #27
0
 /// <summary>
 /// Deserializes the specified string into an object of <paramref name="targetType"/>
 /// </summary>
 public static object Deserialize(this ISerializer serializer, string serialized, Type targetType, ISerializationOptions options = null)
 {
     using (var reader = new StringReader(serialized))
     {
         return(serializer.Deserialize(reader, targetType, options));
     }
 }
 /// <summary>
 /// Initializes a new instance of <see cref="SerializerContractResolver"/>
 /// </summary>
 /// <param name="container">A <see cref="IContainer"/> to use for creating instances of types</param>
 /// <param name="options"><see cref="ISerializationOptions"/> to use during resolving</param>
 public SerializerContractResolver(IContainer container, ISerializationOptions options)
 {
     _container = container;
     _options   = options;
 }
Пример #29
0
 /// <summary>
 /// Initializes a new instance of <see cref="SerializerContractResolver"/>
 /// </summary>
 /// <param name="options"><see cref="ISerializationOptions"/> to use during resolving</param>
 /// <param name="ignoreReadOnlyProperties">Wether or not to ignore read only properties - default false</param>
 public SerializerContractResolver(ISerializationOptions options, bool ignoreReadOnlyProperties = false)
 {
     _options = options;
     _ignoreReadOnlyProperties = ignoreReadOnlyProperties;
 }
Пример #30
0
 /// <summary>
 /// Initializes a new instance of <see cref="SerializerContractResolver"/>
 /// </summary>
 /// <param name="container">A <see cref="IContainer"/> to use for creating instances of types</param>
 /// <param name="options"><see cref="ISerializationOptions"/> to use during resolving</param>
 public SerializerContractResolver(IContainer container, ISerializationOptions options)
 {
     _container = container;
     _options = options;
 }
Пример #31
0
 JsonSerializer CreateSerializerForDeserialization(ISerializationOptions options)
 {
     return(RetrieveSerializer(options ?? SerializationOptions.Default, true));
 }