예제 #1
0
        /// <summary>
        /// 序列化对象为键值对
        /// </summary>
        /// <param name="key">对象名称</param>
        /// <param name="obj">对象实例</param>
        /// <param name="options">选项</param>
        /// <returns></returns>
        public virtual IList <KeyValue> Serialize(string key, object?obj, JsonSerializerOptions?options)
        {
            if (obj == null)
            {
                var keyValue = new KeyValue(key, null);
                return(new List <KeyValue>(1)
                {
                    keyValue
                });
            }

            var jsonOptions = options ?? defaultOptions;

            using var bufferWriter   = new ByteBufferWriter(sizeHint);
            using var utf8JsonWriter = new Utf8JsonWriter(bufferWriter, new JsonWriterOptions
            {
                Indented       = false,
                SkipValidation = true,
                Encoder        = jsonOptions.Encoder
            });

            JsonSerializer.Serialize(utf8JsonWriter, obj, obj.GetType(), options);
            var span           = bufferWriter.GetWrittenSpan();
            var utf8JsonReader = new Utf8JsonReader(span, new JsonReaderOptions
            {
                MaxDepth            = jsonOptions.MaxDepth,
                CommentHandling     = jsonOptions.ReadCommentHandling,
                AllowTrailingCommas = jsonOptions.AllowTrailingCommas,
            });

            return(GetKeyValueList(key, ref utf8JsonReader));
        }