Skip to content

Commit

Permalink
Generate Enum-Dictionary-Keys (analogous to Newtonsoft) (#2825)
Browse files Browse the repository at this point in the history
Generate Enum-Dictionary-Keys (analogous to Newtonsoft, since STJ does support it now).
  • Loading branch information
angelaki authored Apr 24, 2024
1 parent a920aeb commit e97bc2a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,24 @@ public DataContract GetDataContractForType(Type type)

if (IsSupportedDictionary(type, out Type keyType, out Type valueType))
{
IEnumerable<string> keys = null;

if (keyType.IsEnum)
{
// This is a special case where we know the possible key values
var enumValuesAsJson = keyType.GetEnumValues()
.Cast<object>()
.Select(value => JsonConverterFunc(value));

keys = enumValuesAsJson.Any(json => json.StartsWith("\""))
? enumValuesAsJson.Select(json => json.Replace("\"", string.Empty))
: keyType.GetEnumNames();
}

return DataContract.ForDictionary(
underlyingType: type,
valueType: valueType,
keys: null, // STJ doesn't currently support dictionaries with enum key types
keys: keys,
jsonConverter: JsonConverterFunc);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,17 @@ public void GenerateSchema_HonorsSerializerOption_StringEnumConverter(
Assert.Equal(expectedDefaultAsJson, propertySchema.Default.ToJson());
}

[Fact]
public void GenerateSchema_HonorsEnumDictionaryKeys_StringEnumConverter()
{
var subject = Subject();
var schemaRepository = new SchemaRepository();

var referenceSchema = subject.GenerateSchema(typeof(Dictionary<IntEnum, string>), schemaRepository);

Assert.Equal(typeof(IntEnum).GetEnumNames(), referenceSchema.Properties.Keys);
}

[Fact]
public void GenerateSchema_HonorsSerializerAttribute_StringEnumConverter()
{
Expand Down

0 comments on commit e97bc2a

Please sign in to comment.