Example #1
0
        private static JsonConverter <T>?GetConverter <T>(JsonSerializerOptions options)
        {
            if (typeof(T) == typeof(object))
            {
                return(null);
            }

            return(options?.GetConverter(typeof(T)) as JsonConverter <T>);
        }
        /// <summary>
        ///     Initializes a new instance of the <see cref="ConfigurationDictionaryConverter{TElement}" /> class.
        /// </summary>
        /// <param name="options">
        ///     The options controlling the serialization/deserialization.
        /// </param>
        public ConfigurationDictionaryConverter(JsonSerializerOptions options)
        {
            // For performance, use the existing converter if available.
            _valueConverter = (JsonConverter <TElement>)options
                              .GetConverter(typeof(TElement));

            // Cache the key and value types.
            _keyType     = typeof(string);
            _elementType = typeof(TElement);
        }
        public override Option <T> Read(ref Utf8JsonReader reader, System.Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.Null)
            {
                reader.Read();
                return(Option.None <T>());
            }

            return(Option.Some(((JsonConverter <T>)options.GetConverter(typeof(T))).Read(ref reader, typeof(T), options)));
        }
Example #4
0
        public override void Write(Utf8JsonWriter writer, ResolvedEvent value, JsonSerializerOptions options)
        {
            var @event = value.OriginalEvent;

            if (@event == null)
            {
                writer.WriteStartObject();
                writer.WriteEndObject();
                return;
            }

            writer.WriteStartObject();

            writer.WritePropertyName("messageId");
            options.GetConverter <Uuid>().Write(writer, @event.EventId, options);

            writer.WriteString("createdUtc", @event.Created);

            writer.WritePropertyName("position");
            options.GetConverter <Position>().Write(writer, @event.Position, options);

            writer.WriteString("streamId", @event.EventStreamId);

            writer.WritePropertyName("streamVersion");
            options.GetConverter <StreamRevision>()
            .Write(writer, StreamRevision.FromStreamPosition(@event.EventNumber), options);

            writer.WriteString("type", @event.EventType);

            writer.WritePropertyName("payload");
            if (MediaTypeHeaderValue.TryParse(@event.ContentType, out var contentType) &&
                contentType.SubType.EndsWith("json", StringComparison.Ordinal))
            {
                var reader = new Utf8JsonReader(@event.Data.Span);
                if (JsonDocument.TryParseValue(ref reader, out var payload))
                {
                    payload.WriteTo(writer);
                }
                else
                {
                    writer.WriteBase64StringValue(@event.Data.Span);
                }
            }
Example #5
0
        private static T GetValue <T>(ref Utf8JsonReader reader, JsonSerializerOptions options)
        {
            var converter = typeof(T) != typeof(object)
                                ? options?.GetConverter(typeof(T)) as JsonConverter <T>
                                : null;

            return(converter != null
                                ? converter.Read(ref reader, typeof(T), options)
                                : JsonSerializer.Deserialize <T>(ref reader, options));
        }
            public DictionaryEnumConverterInner(JsonSerializerOptions options)
            {
                // For performance, use the existing converter if available.
                _valueConverter = (JsonConverter <TValue>)options
                                  .GetConverter(typeof(TValue));

                // Cache the key and value types.
                _keyType   = typeof(TKey);
                _valueType = typeof(TValue);
            }
 public StringNullableEnumConverter(JsonSerializerOptions options)
 {
     // for performance, use the existing converter if available
     if (options != null)
     {
         _converter = (JsonConverter <T>)options.GetConverter(typeof(T));
     }
     // cache the underlying type
     _underlyingType = Nullable.GetUnderlyingType(typeof(T));
 }
Example #8
0
        public AbstractDictionaryConverter(JsonSerializerOptions options)
        {
            _keyConverter = TypeDescriptor.GetConverter(typeof(TK));
            if (!(_keyConverter.CanConvertFrom(typeof(string)) && _keyConverter.CanConvertTo(typeof(string))))
            {
                throw new JsonException();
            }

            _valueConverter = (JsonConverter <TV>)options.GetConverter(typeof(TV));
        }
Example #9
0
        public override void Write(Utf8JsonWriter writer, AudioAnalysis value, JsonSerializerOptions options)
        {
            var sectionArrayConverter      = options.GetConverter <SectionArray>();
            var segmentArrayConverter      = options.GetConverter <SegmentArray>();
            var timeIntervalArrayConverter = options.GetConverter <TimeIntervalArray>();

            writer.WriteStartObject();
            writer.WriteString("type", "audio_analysis");
            writer.WritePropertyName("bars");
            timeIntervalArrayConverter.Write(writer, value.Bars, options);
            writer.WritePropertyName("beats");
            timeIntervalArrayConverter.Write(writer, value.Beats, options);
            writer.WritePropertyName("sections");
            sectionArrayConverter.Write(writer, value.Sections, options);
            writer.WritePropertyName("segments");
            segmentArrayConverter.Write(writer, value.Segments, options);
            writer.WritePropertyName("tatums");
            timeIntervalArrayConverter.Write(writer, value.Tatums, options);
            writer.WriteEndObject();
        }
Example #10
0
 public ImmutablePointConverter(JsonSerializerOptions options)
 {
     if (options?.GetConverter(typeof(int)) is JsonConverter <int> intConverter)
     {
         _intConverter = intConverter;
     }
     else
     {
         throw new InvalidOperationException();
     }
 }
Example #11
0
        public KeyCombinationConverter(JsonSerializerOptions options)
        {
            if (options?.GetConverter(typeof(int)) is JsonConverter <int> intConverter)
            {
                this.intConverter = intConverter;
            }
            else
            {
                throw new InvalidOperationException();
            }

            if (options?.GetConverter(typeof(bool)) is JsonConverter <bool> boolConverter)
            {
                this.boolConverter = boolConverter;
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
            private static JsonConverter <List <T> > GetKeyConverter(JsonSerializerOptions options)
            {
                var converter = options.GetConverter(typeof(List <T>)) as JsonConverter <List <T> >;

                if (converter is null)
                {
                    throw new JsonException("...");
                }

                return(converter);
            }
        internal static JsonApiRelationshipDetailsConverter <T> GetRelationshipConverter <T>(this JsonSerializerOptions options)
        {
            var converter = options.GetConverter(typeof(RelationshipResource <T>));

            if (converter is not JsonApiRelationshipDetailsConverter <T> jsonApiConverter)
            {
                throw new JsonApiException($"Converter not found for type {typeof(T)}");
            }

            return(jsonApiConverter);
        }
Example #14
0
        public override IReadOnlyDictionary <IndexName, TValue>?Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var converter = options.GetConverter(typeof(ReadOnlyIndexNameDictionary <>).MakeGenericType(typeof(TValue)));

            if (converter is ReadOnlyIndexNameDictionaryConverter <TValue> specialisedConverter)
            {
                return(specialisedConverter.Read(ref reader, typeToConvert, options));
            }

            return(null);
        }
        internal static WrappedJsonConverter <T> GetWrappedConverter <T>(this JsonSerializerOptions options)
        {
            var converter = options.GetConverter(typeof(T));

            if (converter is not WrappedJsonConverter <T> jsonApiConverter)
            {
                throw new JsonApiException($"Converter not found for type {typeof(T)}");
            }

            return(jsonApiConverter);
        }
        private static JsonConverter <T> GetKeyConverter(JsonSerializerOptions options)
        {
            var converter = options.GetConverter(typeof(T)) as JsonConverter <T>;

            if (converter is null)
            {
                throw new JsonException($"No JSON converter for type {typeof(T).Name}");
            }

            return(converter);
        }
        public override T?Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var converter = options.GetConverter(typeof(SourceMarker <>).MakeGenericType(typeToConvert));

            if (converter is SourceConverter <T> sourceConverter)
            {
                var source = sourceConverter.Read(ref reader, typeToConvert, options);
                return(source.Source);
            }

            return(default);
Example #18
0
 public int ReadProperty(ref Utf8JsonReader reader, JsonSerializerOptions options)
 {
     if (options?.GetConverter(typeof(int)) is JsonConverter <int> intConverter)
     {
         reader.Read();
         return(intConverter.Read(ref reader, typeof(int), options));
     }
     else
     {
         throw new JsonException();
     }
 }
        public override void Write(Utf8JsonWriter writer, object?value, JsonSerializerOptions options)
        {
            if (value == null)
            {
                writer.WriteNullValue();
                return;
            }

            JsonConverter jsonConverter = options.GetConverter(value.GetType());

            jsonConverter.GetType().GetMethod("Write") !.Invoke(jsonConverter, new object[] { writer, value, options });
        }
        public ExtensionDataMemberConverter(PropertyInfo propertyInfo, JsonSerializerOptions options)
        {
            if (propertyInfo.GetMethod == null || propertyInfo.SetMethod == null)
            {
                throw new JsonException("Invalid Serialization DataExtension Property");
            }

            Debug.Assert(propertyInfo.IsDefined(typeof(JsonExtensionDataAttribute)));
            _memberGetter         = (Func <T, Dictionary <string, TValue> >)propertyInfo.GetMethod.CreateDelegate(typeof(Func <T, Dictionary <string, TValue> >));
            _memberSetter         = (Action <T, Dictionary <string, TValue> >)propertyInfo.SetMethod.CreateDelegate(typeof(Action <T, Dictionary <string, TValue> >));
            _jsonElementConverter = options.GetConverter <JsonElement>();
        }
        private static void WriteLinks(Utf8JsonWriter writer, IEnumerable <Link> links, JsonSerializerOptions options)
        {
            if (links == null || !links.Any())
            {
                return;
            }

            writer.WritePropertyName("_links");
            var linkConverter = (LinksConverter)options.GetConverter(typeof(IEnumerable <Link>));

            linkConverter.Write(writer, links, options);
        }
Example #22
0
        private static TValue?ReadProperty <TValue>(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions?options)
        {
            // Attempt to use existing converter first before re-entering through JsonSerializer.Deserialize().
            // The default converter for objects does not parse null objects as null, so it is not used here.
            if (typeToConvert != typeof(object) && options?.GetConverter(typeToConvert) is JsonConverter <TValue> valueConverter)
            {
                reader.Read();
                return(valueConverter.Read(ref reader, typeToConvert, options));
            }

            return(JsonSerializer.Deserialize <TValue>(ref reader, options));
        }
Example #23
0
        internal override void WriteWithQuotes(Utf8JsonWriter writer, object value, JsonSerializerOptions options, ref WriteStack state)
        {
            Type          runtimeType      = value.GetType();
            JsonConverter runtimeConverter = options.GetConverter(runtimeType);

            if (runtimeConverter == this)
            {
                ThrowHelper.ThrowNotSupportedException_DictionaryKeyTypeNotSupported(runtimeType, this);
            }

            runtimeConverter.WriteWithQuotesAsObject(writer, value, options, ref state);
        }
    public override object?Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
    {
        var converter = options.GetConverter(typeof(JsonElement)) as JsonConverter <JsonElement>;

        if (converter == null)
        {
            throw new JsonException();
        }
        var jsonEl = converter.Read(ref reader, type, options);

        return(deserializeValue(jsonEl, options));
    }
Example #25
0
        /// <summary>
        /// Gets the default <see cref="JsonSerializerOptions" /> options.
        /// </summary>
        /// <remarks>
        /// When changing these options, update
        ///     Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
        ///         -> AddJellyfinApi
        ///             -> AddJsonOptions.
        /// </remarks>
        /// <returns>The default <see cref="JsonSerializerOptions" /> options.</returns>
        public static JsonSerializerOptions GetOptions()
        {
            var options = new JsonSerializerOptions
            {
                ReadCommentHandling    = JsonCommentHandling.Disallow,
                WriteIndented          = false,
                DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
                NumberHandling         = JsonNumberHandling.AllowReadingFromString
            };

            // Get built-in converters for fallback converting.
            var baseNullableInt32Converter = (JsonConverter <int?>)options.GetConverter(typeof(int?));
            var baseNullableInt64Converter = (JsonConverter <long?>)options.GetConverter(typeof(long?));

            options.Converters.Add(new JsonGuidConverter());
            options.Converters.Add(new JsonStringEnumConverter());
            options.Converters.Add(new JsonNullableStructConverter <int>(baseNullableInt32Converter));
            options.Converters.Add(new JsonNullableStructConverter <long>(baseNullableInt64Converter));

            return(options);
        }
            public DictionaryInt32StringKeyValueConverter(JsonSerializerOptions options)
            {
                if (options == null)
                {
                    throw new ArgumentNullException(nameof(options));
                }

                _intToStringConverter = (JsonConverter <KeyValuePair <int, string> >)options.GetConverter(typeof(KeyValuePair <int, string>));

                // KeyValuePair<> converter is built-in.
                Debug.Assert(_intToStringConverter != null);
            }
Example #27
0
        public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
        {
            Debug.Assert(typeToConvert.GetGenericArguments().Length > 0);

            Type valueTypeToConvert = typeToConvert.GetGenericArguments()[0];

            JsonConverter valueConverter = options.GetConverter(valueTypeToConvert);

            Debug.Assert(valueConverter != null);

            return(CreateValueConverter(valueTypeToConvert, valueConverter));
        }
Example #28
0
        public override void Write(Utf8JsonWriter writer, SearchResult value, JsonSerializerOptions options)
        {
            void WritePaging <TObject>(string propertyName, Paging <TObject>?paging, JsonConverter <Paging <TObject> > converter)
            {
                if (paging is not null)
                {
                    writer.WritePropertyName(propertyName);
                    converter.Write(writer, paging, options);
                }
                else
                {
                    writer.WriteNull(propertyName);
                }
            }

            var artistPagingConverter            = options.GetConverter <Paging <Artist> >();
            var playlistPagingConverter          = options.GetConverter <Paging <Playlist> >();
            var simplifiedAlbumPagingConverter   = options.GetConverter <Paging <SimplifiedAlbum> >();
            var simplifiedEpisodePagingConverter = options.GetConverter <Paging <SimplifiedEpisode> >();
            var simplifiedShowPagingConverter    = options.GetConverter <Paging <SimplifiedShow> >();
            var trackPagingConverter             = options.GetConverter <Paging <Track> >();

            writer.WriteStartObject();
            WritePaging("artists", value.Artists, artistPagingConverter);
            WritePaging("albums", value.Albums, simplifiedAlbumPagingConverter);
            WritePaging("tracks", value.Tracks, trackPagingConverter);
            WritePaging("shows", value.Shows, simplifiedShowPagingConverter);
            WritePaging("episodes", value.Episodes, simplifiedEpisodePagingConverter);
            WritePaging("playlists", value.Playlists, playlistPagingConverter);
            writer.WriteEndObject();
        }
Example #29
0
        /// <summary>
        /// Read Value in the Array
        /// </summary>
        /// <typeparam name="T">Tuple Element Type</typeparam>
        /// <param name="reader">Reader</param>
        /// <param name="options">Existing Options</param>
        /// <returns>Deserialized Value</returns>
        protected T ReadValue <T>(ref Utf8JsonReader reader, JsonSerializerOptions options)
        {
            var converter = (JsonConverter <T>)options.GetConverter(typeof(T));

            if (converter == null)
            {
                return(JsonSerializer.Deserialize <T>(ref reader, options));
            }
            else
            {
                return(converter.Read(ref reader, typeof(T), options));
            }
        }
Example #30
0
        public void TestWhyObjectForWhichNoConverterIsDefinedIsStillConverted()
        {
            var options   = new JsonSerializerOptions();
            var converter = options.GetConverter(typeof(TestClass));

            Contract.Assert(converter == null);
            // ok there's no converter, but why DOES it convert?
            var serialized = JsonSerializer.Serialize(new TestClass());

            Contract.Assert(serialized == "{\"S\":\"S\"}");

            // lesson: apparently there's default JsonConverters in the JsonSerializer which are not in the JsonSerializerOptions.Converters collection...
        }