static JsonSerializerOptions CreateJsonSerializerOptions(JsonIgnoreCondition defaultIgnoreCondition, bool withMagic) { var o = new JsonSerializerOptions { DefaultIgnoreCondition = defaultIgnoreCondition, Converters = { ByteArrayConverter.Instance, Int64Converter.Instance, UInt64Converter.Instance, IsoDateTimeConverter.Instance, DecimalConverter.Instance, BigIntegerConverter.Instance, new JsonStringEnumConverter(), BigFractionConverter.Instance, IPAddressConverter.Instance, DateOnlyConverter.Instance }, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; if (withMagic) { o.Converters.Add(new MagicConverter()); } return(o); }
/// <summary> /// Copies the options from a <see cref="JsonSerializerOptions"/> instance to a new instance. /// </summary> /// <param name="options">The <see cref="JsonSerializerOptions"/> instance to copy options from.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="options"/> is <see langword="null"/>. /// </exception> public JsonSerializerOptions(JsonSerializerOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } _memberAccessorStrategy = options._memberAccessorStrategy; _dictionaryKeyPolicy = options._dictionaryKeyPolicy; _jsonPropertyNamingPolicy = options._jsonPropertyNamingPolicy; _readCommentHandling = options._readCommentHandling; _referenceHandler = options._referenceHandler; _encoder = options._encoder; _defaultIgnoreCondition = options._defaultIgnoreCondition; _defaultBufferSize = options._defaultBufferSize; _maxDepth = options._maxDepth; _allowTrailingCommas = options._allowTrailingCommas; _ignoreNullValues = options._ignoreNullValues; _ignoreReadOnlyProperties = options._ignoreReadOnlyProperties; _ignoreReadonlyFields = options._ignoreReadonlyFields; _includeFields = options._includeFields; _propertyNameCaseInsensitive = options._propertyNameCaseInsensitive; _writeIndented = options._writeIndented; Converters = new ConverterList(this, (ConverterList)options.Converters); EffectiveMaxDepth = options.EffectiveMaxDepth; // _classes is not copied as sharing the JsonClassInfo and JsonPropertyInfo caches can result in // unnecessary references to type metadata, potentially hindering garbage collection on the source options. // _haveTypesBeenCreated is not copied; it's okay to make changes to this options instance as (de)serialization has not occurred. }
/// <summary> /// Creates metadata for a property or field. /// </summary> /// <typeparam name="T">The type that the converter for the property returns or accepts when converting JSON data.</typeparam> /// <returns>A <see cref="JsonPropertyInfo"/> instance intialized with the provided metadata.</returns> public static JsonPropertyInfo CreatePropertyInfo <T>( JsonSerializerOptions options, bool isProperty, Type declaringType, JsonTypeInfo propertyTypeInfo, JsonConverter <T>?converter, Func <object, T>?getter, Action <object, T>?setter, JsonIgnoreCondition ignoreCondition, JsonNumberHandling numberHandling, string propertyName, JsonEncodedText jsonPropertyName) { if (options == null) { throw new ArgumentNullException(nameof(options)); } if (declaringType == null) { throw new ArgumentNullException(nameof(declaringType)); } if (propertyTypeInfo == null) { throw new ArgumentNullException(nameof(propertyTypeInfo)); } if (propertyName == null) { throw new ArgumentNullException(propertyName); } if (converter == null) { converter = propertyTypeInfo.PropertyInfoForTypeInfo.ConverterBase as JsonConverter <T>; if (converter == null) { throw new InvalidOperationException(SR.Format(SR.ConverterForPropertyMustBeValid, declaringType, propertyName, typeof(T))); } } JsonPropertyInfo <T> jsonPropertyInfo = new JsonPropertyInfo <T>(); jsonPropertyInfo.InitializeForSourceGen( options, isProperty, declaringType, propertyTypeInfo, converter, getter, setter, ignoreCondition, numberHandling, propertyName, jsonPropertyName); return(jsonPropertyInfo); }
public void DefaultIgnoreCondition(JsonIgnoreCondition jsonIgnoreCondition, string expectedJson) { JsonSerializerOptions options = new JsonSerializerOptions().SetupExtensions(); options.DefaultIgnoreCondition = jsonIgnoreCondition; string actualJson = JsonSerializer.Serialize(new MyClass(), options); Assert.Equal(expectedJson, actualJson); }
public static JsonSerializerOptions Create(JsonIgnoreCondition ignoreCondition) { JsonSerializerOptions serializerOptions = new() { #if NET5_0_OR_GREATER DefaultIgnoreCondition = (System.Text.Json.Serialization.JsonIgnoreCondition)ignoreCondition, #else IgnoreNullValues = ignoreCondition == JsonIgnoreCondition.WhenWritingNull, #endif }; return(serializerOptions); }
private void DetermineIgnoreConditionInternal(JsonIgnoreCondition ignoreCondition) { switch (ignoreCondition) { case JsonIgnoreCondition.WhenWritingDefault: IgnoreDefaultValuesForReferenceTypesOnWrite = true; IgnoreDefaultValuesForValueTypesOnWrite = true; break; case JsonIgnoreCondition.WhenWritingNull: IgnoreDefaultValuesForReferenceTypesOnWrite = true; break; } }
public void Serialize_ShouldRespectJsonIgnoreCondition(JsonIgnoreCondition condition) { var options = new JsonSerializerOptions { DefaultIgnoreCondition = condition, }; var instance = new DefaultIgnoreCondition(); var context = new Context <DefaultIgnoreCondition>( instance, new JsonSerializerOptions(options) ); var expected = JsonSerializer.Serialize(instance, options); var actual = context.Json; Assert.Equal(expected, actual); }
private void DetermineIgnoreCondition() { JsonIgnoreAttribute?ignoreAttribute; if (PropertyInfo != null && (ignoreAttribute = GetAttribute <JsonIgnoreAttribute>(PropertyInfo)) != null) { JsonIgnoreCondition condition = ignoreAttribute.Condition; // We should have created a placeholder property for this upstream and shouldn't be down this code-path. Debug.Assert(condition != JsonIgnoreCondition.Always); if (condition != JsonIgnoreCondition.Never) { Debug.Assert(condition == JsonIgnoreCondition.WhenNull); IgnoreNullValues = true; } } else { IgnoreNullValues = Options.IgnoreNullValues; } }
/// <summary> /// Copies the options from a <see cref="JsonSerializerOptions"/> instance to a new instance. /// </summary> /// <param name="options">The <see cref="JsonSerializerOptions"/> instance to copy options from.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="options"/> is <see langword="null"/>. /// </exception> public JsonSerializerOptions(JsonSerializerOptions options) { if (options is null) { ThrowHelper.ThrowArgumentNullException(nameof(options)); } _memberAccessorStrategy = options._memberAccessorStrategy; _dictionaryKeyPolicy = options._dictionaryKeyPolicy; _jsonPropertyNamingPolicy = options._jsonPropertyNamingPolicy; _readCommentHandling = options._readCommentHandling; _referenceHandler = options._referenceHandler; _converters = new ConverterList(this, options._converters); _encoder = options._encoder; _defaultIgnoreCondition = options._defaultIgnoreCondition; _numberHandling = options._numberHandling; _unknownTypeHandling = options._unknownTypeHandling; _defaultBufferSize = options._defaultBufferSize; _maxDepth = options._maxDepth; _allowTrailingCommas = options._allowTrailingCommas; _ignoreNullValues = options._ignoreNullValues; _ignoreReadOnlyProperties = options._ignoreReadOnlyProperties; _ignoreReadonlyFields = options._ignoreReadonlyFields; _includeFields = options._includeFields; _propertyNameCaseInsensitive = options._propertyNameCaseInsensitive; _writeIndented = options._writeIndented; // Preserve backward compatibility with .NET 6 // This should almost certainly be changed, cf. https://github.com/dotnet/aspnetcore/issues/38720 _typeInfoResolver = options._typeInfoResolver is JsonSerializerContext ? null : options._typeInfoResolver; EffectiveMaxDepth = options.EffectiveMaxDepth; ReferenceHandlingStrategy = options.ReferenceHandlingStrategy; // _cachingContext is not copied as sharing the JsonTypeInfo and JsonPropertyInfo caches can result in // unnecessary references to type metadata, potentially hindering garbage collection on the source options. TrackOptionsInstance(this); }
internal void InitializeForSourceGen( JsonSerializerOptions options, bool isProperty, Type declaringType, JsonTypeInfo typeInfo, JsonConverter <T> converter, Func <object, T>?getter, Action <object, T>?setter, JsonIgnoreCondition ignoreCondition, JsonNumberHandling numberHandling, string propertyName, string?jsonPropertyName) { Options = options; ClrName = propertyName; // Property name settings. if (jsonPropertyName != null) { NameAsString = jsonPropertyName; } else if (options.PropertyNamingPolicy == null) { NameAsString = ClrName; } else { NameAsString = options.PropertyNamingPolicy.ConvertName(ClrName); if (NameAsString == null) { ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameNull(DeclaringType, this); } } NameAsUtf8Bytes ??= Encoding.UTF8.GetBytes(NameAsString !); EscapedNameSection ??= JsonHelpers.GetEscapedPropertyNameSection(NameAsUtf8Bytes, Options.Encoder); if (ignoreCondition == JsonIgnoreCondition.Always) { IsIgnored = true; Debug.Assert(!ShouldSerialize); Debug.Assert(!ShouldDeserialize); } else { Get = getter; Set = setter; HasGetter = Get != null; HasSetter = Set != null; ConverterBase = converter; RuntimeTypeInfo = typeInfo; DeclaredPropertyType = typeof(T); DeclaringType = declaringType; IgnoreCondition = ignoreCondition; MemberType = isProperty ? MemberTypes.Property : MemberTypes.Field; _converterIsExternalAndPolymorphic = !converter.IsInternalConverter && DeclaredPropertyType != converter.TypeToConvert; PropertyTypeCanBeNull = typeof(T).CanBeNull(); _propertyTypeEqualsTypeToConvert = converter.TypeToConvert == typeof(T); ConverterStrategy = Converter !.ConverterStrategy; RuntimePropertyType = DeclaredPropertyType; DetermineIgnoreCondition(IgnoreCondition); // TODO: this method needs to also take the number handling option for the declaring type. DetermineNumberHandlingForProperty(numberHandling, declaringTypeNumberHandling: null); DetermineSerializationCapabilities(IgnoreCondition); } }
public static string ToJson( this object self, bool indented = false, JsonIgnoreCondition ignoreCondition = JsonIgnoreCondition.Never)