Пример #1
0
        public static string SerializeObject(
            this IXmlSerializerInternal serializer,
            object instance,
            Encoding encoding,
            Formatting formatting,
            ISerializeOptions options)
        {
            options = options.WithNewSerializationState();

            var sb = new StringBuilder();

            using (var stringWriter = new StringWriterWithEncoding(sb, encoding ?? Encoding.UTF8))
            {
                using (var xmlWriter = new XSerializerXmlTextWriter(stringWriter, options))
                {
                    xmlWriter.Formatting = formatting;
                    serializer.SerializeObject(xmlWriter, instance, options);
                }
            }

            return(sb.ToString());
        }
        private void WriteIDictionaryOfAnythingToAnything(JsonWriter writer, object instance, IJsonSerializeOperationInfo info)
        {
            writer.WriteOpenObject();

            var dictionary = (IEnumerable)instance;

            var first = true;

            Func<object, object> getKeyFunc = null;
            Func<object, object> getValueFunc = null;

            foreach (var item in dictionary)
            {
                if (first)
                {
                    first = false;
                    var itemType = item.GetType();
                    getKeyFunc = _getKeyFuncCache.GetOrAdd(itemType, GetGetKeyFunc);
                    getValueFunc = _getValueFuncCache.GetOrAdd(itemType, GetGetValueFunc);
                }
                else
                {
                    writer.WriteItemSeparator();
                }

                var key = getKeyFunc(item);

                var keyString = key as string;
                if (keyString != null)
                {
                    writer.WriteValue(keyString);
                }
                else
                {
                    var sb = new StringBuilder();

                    using (var stringWriter = new StringWriterWithEncoding(sb, Encoding.UTF8))
                    {
                        using (var keyWriter = new JsonWriter(stringWriter, info))
                        {
                            _keySerializer.SerializeObject(keyWriter, key, info);
                        }
                    }

                    writer.WriteValue((sb.ToString()));
                }

                writer.WriteNameValueSeparator();
                _valueSerializer.SerializeObject(writer, getValueFunc(item), info);
            }

            writer.WriteCloseObject();
        }