Exemple #1
0
            /// <summary>
            /// Initializes a new instance of the <see cref="Serializer" /> class.
            /// </summary>
            /// <param name="obj">The object.</param>
            /// <param name="depth">The depth.</param>
            /// <param name="options">The options.</param>
            private Serializer(object obj, int depth, SerializerOptions options)
            {
                if (depth > 20)
                {
                    throw new InvalidOperationException(
                              "The max depth (20) has been reached. Serializer can not continue.");
                }

                // Basic Type Handling (nulls, strings, number, date and bool)
                _result = ResolveBasicType(obj);

                if (string.IsNullOrWhiteSpace(_result) == false)
                {
                    return;
                }

                _options         = options;
                _lastCommaSearch = FieldSeparatorChar + (_options.Format ? Environment.NewLine : string.Empty);

                // Handle circular references correctly and avoid them
                if (options.IsObjectPresent(obj))
                {
                    _result = $"{{ \"$circref\": \"{Escape(obj.GetHashCode().ToStringInvariant(), false)}\" }}";
                    return;
                }

                // At this point, we will need to construct the object with a StringBuilder.
                _builder = new StringBuilder();

                switch (obj)
                {
                case IDictionary itemsZero when itemsZero.Count == 0:
                    _result = EmptyObjectLiteral;
                    break;

                case IDictionary items:
                    _result = ResolveDictionary(items, depth);
                    break;

                case IEnumerable enumerableZero when !enumerableZero.Cast <object>().Any():
                    _result = EmptyArrayLiteral;
                    break;

                case IEnumerable enumerableBytes when enumerableBytes is byte[] bytes:
                    _result = Serialize(bytes.ToBase64(), depth, _options);
                    break;

                case IEnumerable enumerable:
                    _result = ResolveEnumerable(enumerable, depth);
                    break;

                default:
                    _result = ResolveObject(obj, depth);
                    break;
                }
            }