Exemple #1
0
            private Converter(object source,
                              Type targetType,
                              ref object targetInstance,
                              bool includeNonPublic,
                              JsonSerializerCase jsonSerializerCase)
            {
                _targetType = targetInstance != null?targetInstance.GetType() : targetType;

                _includeNonPublic   = includeNonPublic;
                _jsonSerializerCase = jsonSerializerCase;

                if (source == null)
                {
                    return;
                }

                var sourceType = source.GetType();

                if (_targetType == null || _targetType == typeof(object))
                {
                    _targetType = sourceType;
                }
                if (sourceType == _targetType)
                {
                    _target = source;
                    return;
                }

                if (!TrySetInstance(targetInstance, source, ref _target))
                {
                    return;
                }

                ResolveObject(source, ref _target);
            }
Exemple #2
0
        /// <summary>
        /// Serializes the specified object into a JSON string.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <param name="format">if set to <c>true</c> it formats and indents the output.</param>
        /// <param name="typeSpecifier">The type specifier. Leave null or empty to avoid setting.</param>
        /// <param name="includeNonPublic">if set to <c>true</c> non-public getters will be also read.</param>
        /// <param name="includedNames">The included property names.</param>
        /// <param name="excludedNames">The excluded property names.</param>
        /// <param name="parentReferences">The parent references.</param>
        /// <param name="jsonSerializerCase">The json serializer case.</param>
        /// <returns>
        /// A <see cref="System.String" /> that represents the current object.
        /// </returns>
        public static string Serialize(
            object?obj,
            bool format,
            string?typeSpecifier,
            bool includeNonPublic,
            string[]?includedNames,
            string[]?excludedNames,
            List <WeakReference>?parentReferences,
            JsonSerializerCase jsonSerializerCase)
        {
            if (obj != null && (obj is string || Definitions.AllBasicValueTypes.Contains(obj.GetType())))
            {
                return(SerializePrimitiveValue(obj));
            }

            var options = new SerializerOptions(
                format,
                typeSpecifier,
                includedNames,
                GetExcludedNames(obj?.GetType(), excludedNames),
                includeNonPublic,
                parentReferences,
                jsonSerializerCase);

            return(Serialize(obj, options));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SerializerOptions"/> class.
        /// </summary>
        /// <param name="format">if set to <c>true</c> [format].</param>
        /// <param name="typeSpecifier">The type specifier.</param>
        /// <param name="includeProperties">The include properties.</param>
        /// <param name="excludeProperties">The exclude properties.</param>
        /// <param name="includeNonPublic">if set to <c>true</c> [include non public].</param>
        /// <param name="parentReferences">The parent references.</param>
        /// <param name="jsonSerializerCase">The json serializer case.</param>
        public SerializerOptions(
            bool format,
            string?typeSpecifier,
            string[]?includeProperties,
            string[]?excludeProperties = null,
            bool includeNonPublic      = true,
            IReadOnlyCollection <WeakReference>?parentReferences = null,
            JsonSerializerCase jsonSerializerCase = JsonSerializerCase.None)
        {
            _includeProperties = includeProperties;

            ExcludeProperties  = excludeProperties;
            IncludeNonPublic   = includeNonPublic;
            Format             = format;
            TypeSpecifier      = typeSpecifier;
            JsonSerializerCase = jsonSerializerCase;

            if (parentReferences == null)
            {
                return;
            }

            foreach (var parentReference in parentReferences.Where(x => x.IsAlive))
            {
                IsObjectPresent(parentReference.Target);
            }
        }
Exemple #4
0
            internal static object?FromJsonResult(
                object?source,
                JsonSerializerCase jsonSerializerCase,
                Type?targetType       = null,
                bool includeNonPublic = false)
            {
                object?nullRef = null;

                return(new Converter(source, targetType ?? typeof(object), ref nullRef, includeNonPublic, jsonSerializerCase).GetResult());
            }
Exemple #5
0
        internal static string GetNameWithCase(this string name, JsonSerializerCase jsonSerializerCase)
        {
            switch (jsonSerializerCase)
            {
            case JsonSerializerCase.PascalCase:
                return(char.ToUpperInvariant(name[0]) + name.Substring(1));

            case JsonSerializerCase.CamelCase:
                return(char.ToLowerInvariant(name[0]) + name.Substring(1));

            case JsonSerializerCase.None:
                return(name);

            default:
                throw new ArgumentOutOfRangeException(nameof(jsonSerializerCase), jsonSerializerCase, null);
            }
        }
        private static async Task <TData> JsonInternal <TData>(IHttpContext context, JsonSerializerCase jsonSerializerCase)
        {
            string body;

            using (var reader = context.OpenRequestText())
            {
                body = await reader.ReadToEndAsync().ConfigureAwait(false);
            }

            try
            {
                return(Swan.Formatters.Json.Deserialize <TData>(body, jsonSerializerCase));
            }
            catch (FormatException)
            {
                $"[{context.Id}] Cannot convert JSON request body to {typeof(TData).Name}, sending 400 Bad Request..."
                .Warn($"{nameof(RequestDeserializer)}.{nameof(Json)}");

                throw HttpException.BadRequest("Incorrect request data format.");
            }
        }
Exemple #7
0
 /// <summary>
 /// Deserializes the specified JSON string and converts it to the specified object type.
 /// </summary>
 /// <param name="json">The JSON string.</param>
 /// <param name="resultType">Type of the result.</param>
 /// <param name="includeNonPublic">if set to true, it also uses the non-public constructors and property setters.</param>
 /// <param name="jsonSerializerCase">The json serializer case.</param>
 /// <returns>
 /// Type of the current conversion from json result.
 /// </returns>
 public static object?Deserialize(string json, Type resultType, bool includeNonPublic = false, JsonSerializerCase jsonSerializerCase = JsonSerializerCase.None)
 => Converter.FromJsonResult(Deserializer.DeserializeInternal(json), jsonSerializerCase, resultType, includeNonPublic);
Exemple #8
0
 /// <summary>
 /// Deserializes the specified JSON string and converts it to the specified object type.
 /// Non-public constructors and property setters are ignored.
 /// </summary>
 /// <typeparam name="T">The type of object to deserialize.</typeparam>
 /// <param name="json">The JSON string.</param>
 /// <param name="jsonSerializerCase">The JSON serializer case.</param>
 /// <returns>
 /// The deserialized specified type object.
 /// </returns>
 /// <example>
 /// The following code describes how to deserialize a JSON string into an object of type T.
 /// <code>
 /// using Swan.Formatters;
 /// class Example
 /// {
 /// static void Main()
 /// {
 /// // json type BasicJson to serialize
 /// var basicJson = "{\"One\":\"One\",\"Two\":\"Two\",\"Three\":\"Three\"}";
 /// // deserializes the specified string in a new instance of the type BasicJson.
 /// var data = Json.Deserialize&lt;BasicJson&gt;(basicJson);
 /// }
 /// }
 /// </code></example>
 public static T Deserialize <T>(string json, JsonSerializerCase jsonSerializerCase = JsonSerializerCase.None)
 => (T)Deserialize(json, typeof(T), jsonSerializerCase: jsonSerializerCase);
Exemple #9
0
 /// <summary>
 /// Deserializes the specified json string as either a Dictionary[string, object] or as a List[object]
 /// depending on the syntax of the JSON string.
 /// </summary>
 /// <param name="json">The JSON string.</param>
 /// <param name="jsonSerializerCase">The json serializer case.</param>
 /// <returns>
 /// Type of the current deserializes.
 /// </returns>
 /// <example>
 /// The following code shows how to deserialize a JSON string into a Dictionary.
 /// <code>
 /// using Swan.Formatters;
 /// class Example
 /// {
 /// static void Main()
 /// {
 /// // json to deserialize
 /// var basicJson = "{\"One\":\"One\",\"Two\":\"Two\",\"Three\":\"Three\"}";
 /// // deserializes the specified json into a Dictionary&lt;string, object&gt;.
 /// var data = Json.Deserialize(basicJson, JsonSerializerCase.None);
 /// }
 /// }
 /// </code></example>
 public static object?Deserialize(
     string json,
     JsonSerializerCase jsonSerializerCase)
 => Converter.FromJsonResult(Deserializer.DeserializeInternal(json), jsonSerializerCase);
Exemple #10
0
 /// <summary>
 /// Serializes the specified object into a JSON string.
 /// </summary>
 /// <param name="obj">The object.</param>
 /// <param name="jsonSerializerCase">The json serializer case.</param>
 /// <param name="format">if set to <c>true</c> [format].</param>
 /// <param name="typeSpecifier">The type specifier.</param>
 /// <returns>
 /// A <see cref="System.String" /> that represents the current object.
 /// </returns>
 public static string Serialize(
     object?obj,
     JsonSerializerCase jsonSerializerCase,
     bool format          = false,
     string?typeSpecifier = null) => Serialize(obj, format, typeSpecifier, false, null, null, null, jsonSerializerCase);
Exemple #11
0
 /// <summary>
 /// Serializes data in JSON format with the specified <paramref name="jsonSerializerCase"/>
 /// to a HTTP response, using the <see cref="Swan.Formatters.Json"/> utility class.
 /// </summary>
 /// <param name="jsonSerializerCase">The JSON serializer case.</param>
 /// <returns>A <see cref="ResponseSerializerCallback"/> that can be used to serialize
 /// data to a HTTP response.</returns>
 public static ResponseSerializerCallback Json(JsonSerializerCase jsonSerializerCase)
 => async(context, data) => {
Exemple #12
0
 internal static string GetNameWithCase(this string name, JsonSerializerCase jsonSerializerCase) =>
 jsonSerializerCase switch
 {
 /// <summary>
 /// Returns a <see cref="RequestDeserializerCallback{TData}">RequestDeserializerCallback</see>
 /// that will deserialize an HTTP request body in JSON format, using the specified property name casing.
 /// </summary>
 /// <typeparam name="TData">The expected type of the deserialized data.</typeparam>
 /// <param name="jsonSerializerCase">The <see cref="JsonSerializerCase"/> to use.</param>
 /// <returns>A <see cref="RequestDeserializerCallback{TData}"/> that can be used to deserialize
 /// a JSON request body.</returns>
 public static RequestDeserializerCallback <TData> Json <TData>(JsonSerializerCase jsonSerializerCase)
 => context => JsonInternal <TData>(context, jsonSerializerCase);
Exemple #14
0
 /// <summary>
 /// Deserializes the specified JSON string and converts it to the specified object type.
 /// </summary>
 /// <param name="json">The JSON string.</param>
 /// <param name="resultType">Type of the result.</param>
 /// <param name="includeNonPublic">if set to true, it also uses the non-public constructors and property setters.</param>
 /// <param name="jsonSerializerCase">The json serializer case.</param>
 /// <returns>
 /// Type of the current conversion from json result.
 /// </returns>
 public static object?Deserialize(string json, Type resultType, bool includeNonPublic = false, JsonSerializerCase jsonSerializerCase = JsonSerializerCase.None) =>
 json == null
         ? throw new ArgumentNullException(nameof(json))
         : Converter.FromJsonResult(
           Deserializer.DeserializeInternal(json),
           jsonSerializerCase,
           resultType,
           includeNonPublic);
Exemple #15
0
 /// <summary>
 /// Deserializes the specified JSON string and converts it to the specified object type.
 /// Non-public constructors and property setters are ignored.
 /// </summary>
 /// <typeparam name="T">The type of object to deserialize.</typeparam>
 /// <param name="json">The JSON string.</param>
 /// <param name="jsonSerializerCase">The JSON serializer case.</param>
 /// <returns>
 /// The deserialized specified type object.
 /// </returns>
 /// <example>
 /// The following code describes how to deserialize a JSON string into an object of type T.
 /// <code>
 /// using Swan.Formatters;
 /// class Example
 /// {
 /// static void Main()
 /// {
 /// // json type BasicJson to serialize
 /// var basicJson = "{\"One\":\"One\",\"Two\":\"Two\",\"Three\":\"Three\"}";
 /// // deserializes the specified string in a new instance of the type BasicJson.
 /// var data = Json.Deserialize&lt;BasicJson&gt;(basicJson);
 /// }
 /// }
 /// </code></example>
 public static T Deserialize <T>(string json, JsonSerializerCase jsonSerializerCase = JsonSerializerCase.None) =>
 json == null
         ? throw new ArgumentNullException(nameof(json))
         : (T)Deserialize(json, typeof(T), jsonSerializerCase: jsonSerializerCase);
Exemple #16
0
 /// <summary>
 /// Deserializes the specified json string as either a Dictionary[string, object] or as a List[object]
 /// depending on the syntax of the JSON string.
 /// </summary>
 /// <param name="json">The JSON string.</param>
 /// <param name="jsonSerializerCase">The json serializer case.</param>
 /// <returns>
 /// Type of the current deserializes.
 /// </returns>
 /// <example>
 /// The following code shows how to deserialize a JSON string into a Dictionary.
 /// <code>
 /// using Swan.Formatters;
 /// class Example
 /// {
 /// static void Main()
 /// {
 /// // json to deserialize
 /// var basicJson = "{\"One\":\"One\",\"Two\":\"Two\",\"Three\":\"Three\"}";
 /// // deserializes the specified json into a Dictionary&lt;string, object&gt;.
 /// var data = Json.Deserialize(basicJson, JsonSerializerCase.None);
 /// }
 /// }
 /// </code></example>
 public static object?Deserialize(string json, JsonSerializerCase jsonSerializerCase) =>
 json == null
         ? throw new ArgumentNullException(nameof(json))
         : Converter.FromJsonResult(Deserializer.DeserializeInternal(json), jsonSerializerCase);