Skip to content

Commit

Permalink
.
Browse files Browse the repository at this point in the history
  • Loading branch information
seungyongshim committed Apr 8, 2024
1 parent fbb6f20 commit 7ee4fb3
Showing 1 changed file with 15 additions and 20 deletions.
35 changes: 15 additions & 20 deletions src/SystemTextJsonNullTests/UnitTest1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@ namespace SystemTextJsonNullTests;

public class UnitTest1
{




public static JsonSerializerOptions JsonSerializerOptions { get; } = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Expand All @@ -24,12 +20,8 @@ public class UnitTest1
}
};

static void InterceptNullSetter(JsonTypeInfo typeInfo)
public static void InterceptNullSetter(JsonTypeInfo typeInfo)
{
static bool IsRequiredMember(JsonPropertyInfo propertyInfo) =>
propertyInfo.AttributeProvider?.GetCustomAttributes(typeof(System.Runtime.CompilerServices.RequiredMemberAttribute), true).Any() ?? false;


foreach (var (propertyInfo, setProperty) in from propertyInfo in typeInfo.Properties
let setProperty = propertyInfo.Set
where setProperty is not null
Expand All @@ -39,21 +31,12 @@ static void InterceptNullSetter(JsonTypeInfo typeInfo)
{
if (value is null)
{
if (IsRequiredMember(propertyInfo))
if (propertyInfo.IsRequired)
{
throw new JsonException($"Null value not allowed for '{propertyInfo.Name}'");
}
NullabilityInfoContext context = new();
var nullabilityInfo = propertyInfo.AttributeProvider switch
{
FieldInfo fieldInfo => context.Create(fieldInfo),
PropertyInfo propertyInfo => context.Create(propertyInfo),
_ => null
};
if (nullabilityInfo?.WriteState is NullabilityState.Nullable)
if (NullabilityInfo(propertyInfo)?.WriteState is NullabilityState.Nullable)
{
setProperty(obj, value);
}
Expand All @@ -64,6 +47,18 @@ static void InterceptNullSetter(JsonTypeInfo typeInfo)
}
};
}

static NullabilityInfo? NullabilityInfo(JsonPropertyInfo value)
{
NullabilityInfoContext context = new();

return value.AttributeProvider switch
{
FieldInfo fieldInfo => context.Create(fieldInfo),
PropertyInfo propertyInfo => context.Create(propertyInfo),
_ => null
};
}
}

[Fact]
Expand Down

0 comments on commit 7ee4fb3

Please sign in to comment.