Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{#allowableValues}}{{#enumVars}}{{#-first}}{{#isNumeric}}{{#isLong}}GetInt64{{/isLong}}{{#isFloat}}GetSingle{{/isFloat}}{{#isDouble}}GetDouble{{/isDouble}}{{#isDecimal}}GetDecimal{{/isDecimal}}{{^isLong}}{{^isFloat}}{{^isDouble}}{{^isDecimal}}GetInt32{{/isDecimal}}{{/isDouble}}{{/isFloat}}{{/isLong}}{{/isNumeric}}{{/-first}}{{/enumVars}}{{/allowableValues}}
131 changes: 127 additions & 4 deletions modules/openapi-generator/src/main/resources/csharp/modelEnum.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
{{/-first}}
{{/enumVars}}
{{/allowableValues}}
{{>visibility}} enum {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{#vendorExtensions.x-enum-byte}}: byte{{/vendorExtensions.x-enum-byte}}
{{>visibility}} enum {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{#vendorExtensions.x-enum-byte}} : byte{{/vendorExtensions.x-enum-byte}}{{#isLong}} : long{{/isLong}}
{
{{#allowableValues}}
{{#enumVars}}
Expand Down Expand Up @@ -90,9 +90,42 @@
/// <exception cref="NotImplementedException"></exception>
{{>visibility}} static {{>EnumValueDataType}} ToJsonValue({{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} value)
{
{{^isString}}
{{#isInteger}}
return ({{>EnumValueDataType}}) value;
{{/isString}}
{{/isInteger}}
{{#isLong}}
return ({{>EnumValueDataType}}) value;
{{/isLong}}
{{#isFloat}}
{{#allowableValues}}
{{#enumVars}}
if (value == {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.{{name}})
return {{{value}}}f;

{{/enumVars}}
{{/allowableValues}}
throw new NotImplementedException($"Value could not be handled: '{value}'");
{{/isFloat}}
{{#isDouble}}
{{#allowableValues}}
{{#enumVars}}
if (value == {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.{{name}})
return {{{value}}}d;

{{/enumVars}}
{{/allowableValues}}
throw new NotImplementedException($"Value could not be handled: '{value}'");
{{/isDouble}}
{{#isDecimal}}
{{#allowableValues}}
{{#enumVars}}
if (value == {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.{{name}})
return {{{value}}}m;

{{/enumVars}}
{{/allowableValues}}
throw new NotImplementedException($"Value could not be handled: '{value}'");
{{/isDecimal}}
{{#isString}}
{{#allowableValues}}
{{#enumVars}}
Expand Down Expand Up @@ -121,6 +154,42 @@
/// <returns></returns>
public override {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
{{#isInteger}}
string rawValue = reader.{{>EnumJsonReaderMethod}}().ToString();
{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? result = {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.FromStringOrDefault(rawValue);
if (result != null)
return result.Value;
throw new JsonException();
{{/isInteger}}
{{#isLong}}
string rawValue = reader.{{>EnumJsonReaderMethod}}().ToString();
{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? result = {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.FromStringOrDefault(rawValue);
if (result != null)
return result.Value;
throw new JsonException();
{{/isLong}}
{{#isFloat}}
string rawValue = reader.GetSingle().ToString();
{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? result = {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.FromStringOrDefault(rawValue);
if (result != null)
return result.Value;
throw new JsonException();
{{/isFloat}}
{{#isDouble}}
string rawValue = reader.GetDouble().ToString();
{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? result = {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.FromStringOrDefault(rawValue);
if (result != null)
return result.Value;
throw new JsonException();
{{/isDouble}}
{{#isDecimal}}
string rawValue = reader.GetDecimal().ToString();
{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? result = {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.FromStringOrDefault(rawValue);
if (result != null)
return result.Value;
throw new JsonException();
{{/isDecimal}}
{{#isString}}
string{{nrt?}} rawValue = reader.GetString();

{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? result = rawValue == null
Expand All @@ -131,6 +200,7 @@
return result.Value;

throw new JsonException();
{{/isString}}
}

/// <summary>
Expand All @@ -141,7 +211,12 @@
/// <param name="options"></param>
public override void Write(Utf8JsonWriter writer, {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} {{#lambda.camelcase_sanitize_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_sanitize_param}}, JsonSerializerOptions options)
{
{{^isString}}
writer.WriteNumberValue({{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_sanitize_param}}));
{{/isString}}
{{#isString}}
writer.WriteStringValue({{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_sanitize_param}}).ToString());
{{/isString}}
}
}

Expand All @@ -159,6 +234,45 @@
/// <returns></returns>
public override {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null)
return null;

{{#isInteger}}
string rawValue = reader.{{>EnumJsonReaderMethod}}().ToString();
{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? result = {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.FromStringOrDefault(rawValue);
if (result != null)
return result.Value;
throw new JsonException();
{{/isInteger}}
{{#isLong}}
string rawValue = reader.{{>EnumJsonReaderMethod}}().ToString();
{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? result = {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.FromStringOrDefault(rawValue);
if (result != null)
return result.Value;
throw new JsonException();
{{/isLong}}
{{#isFloat}}
string rawValue = reader.GetSingle().ToString();
{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? result = {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.FromStringOrDefault(rawValue);
if (result != null)
return result.Value;
throw new JsonException();
{{/isFloat}}
{{#isDouble}}
string rawValue = reader.GetDouble().ToString();
{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? result = {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.FromStringOrDefault(rawValue);
if (result != null)
return result.Value;
throw new JsonException();
{{/isDouble}}
{{#isDecimal}}
string rawValue = reader.GetDecimal().ToString();
{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? result = {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.FromStringOrDefault(rawValue);
if (result != null)
return result.Value;
throw new JsonException();
{{/isDecimal}}
{{#isString}}
string{{nrt?}} rawValue = reader.GetString();

{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? result = rawValue == null
Expand All @@ -169,6 +283,7 @@
return result.Value;

throw new JsonException();
{{/isString}}
Comment on lines 275 to 286
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot
In @tools/openapi/templates/csharp/modelEnum.mustache around lines 277 - 288,
The NullableJsonConverter.Read implementation for string-backed enums should
detect a JSON null token before calling reader.GetString and return null rather
than throwing; update the isString branch in the NullableJsonConverter.Read
method to check reader.TokenType == JsonTokenType.Null (or check rawValue ==
null immediately after GetString) and return null when appropriate, then only
call ValueConverter.FromStringOrDefault(rawValue) for non-null rawValue so that
deserializing JSON null yields a null nullable enum instead of raising
JsonException.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 383ea387. The JsonTokenType.Null check is now applied to ALL enum types (including string) in the nullable converter Read method. Previously it was gated behind {{^isString}}, so string enums would fall through to reader.GetString() and then throw JsonException when the result was null. Now it returns null immediately for null tokens.

}

/// <summary>
Expand All @@ -179,7 +294,15 @@
/// <param name="options"></param>
public override void Write(Utf8JsonWriter writer, {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}? {{#lambda.camelcase_sanitize_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_sanitize_param}}, JsonSerializerOptions options)
{
writer.WriteStringValue({{#lambda.camelcase_sanitize_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_sanitize_param}}.HasValue ? {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_sanitize_param}}.Value).ToString() : "null");
if ({{#lambda.camelcase_sanitize_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_sanitize_param}}.HasValue)
{{^isString}}
writer.WriteNumberValue({{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_sanitize_param}}.Value));
{{/isString}}
{{#isString}}
writer.WriteStringValue({{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}ValueConverter.ToJsonValue({{#lambda.camelcase_sanitize_param}}{{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{/lambda.camelcase_sanitize_param}}.Value).ToString());
{{/isString}}
else
writer.WriteNullValue();
}
}
{{/useGenericHost}}
Original file line number Diff line number Diff line change
Expand Up @@ -260,4 +260,82 @@ private List<String> getNames(List<CodegenProperty> props) {
if (props == null) return null;
return props.stream().map(v -> v.name).collect(Collectors.toList());
}

@Test
public void testIntegerEnumJsonConverterUsesNumericOperations() throws IOException {
File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
output.deleteOnExit();
final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/csharp/integer-enum.yaml");
final DefaultGenerator defaultGenerator = new DefaultGenerator();
final ClientOptInput clientOptInput = new ClientOptInput();
clientOptInput.openAPI(openAPI);
CSharpClientCodegen cSharpClientCodegen = new CSharpClientCodegen();
cSharpClientCodegen.setLibrary("generichost");
cSharpClientCodegen.setOutputDir(output.getAbsolutePath());
clientOptInput.config(cSharpClientCodegen);
defaultGenerator.opts(clientOptInput);

Map<String, File> files = defaultGenerator.generate().stream()
.collect(Collectors.toMap(File::getPath, Function.identity()));

// Verify integer enum uses numeric JSON reader with validation
File intEnumFile = files.get(Paths
.get(output.getAbsolutePath(), "src", "Org.OpenAPITools", "Model", "IntegerEnum.cs")
.toString()
);
assertNotNull(intEnumFile, "Could not find file for model: IntegerEnum");
assertFileContains(intEnumFile.toPath(),
"reader.GetInt32().ToString()",
"FromStringOrDefault(rawValue)",
"throw new JsonException()",
"writer.WriteNumberValue(",
"public static int ToJsonValue(IntegerEnum value)"
);
assertFileNotContains(intEnumFile.toPath(),
"reader.GetString()",
"writer.WriteStringValue(",
": long",
": byte"
);

// Verify long enum uses int64 reader with validation and actual int64 values
File longEnumFile = files.get(Paths
.get(output.getAbsolutePath(), "src", "Org.OpenAPITools", "Model", "LongEnum.cs")
.toString()
);
assertNotNull(longEnumFile, "Could not find file for model: LongEnum");
assertFileContains(longEnumFile.toPath(),
"enum LongEnum : long",
"reader.GetInt64().ToString()",
"FromStringOrDefault(rawValue)",
"throw new JsonException()",
"writer.WriteNumberValue(",
"public static long ToJsonValue(LongEnum value)",
"AboveInt32Max = 2147483648",
"Int64Max = 9223372036854775807"
);
assertFileNotContains(longEnumFile.toPath(),
"reader.GetString()",
"writer.WriteStringValue("
);

// Verify double enum reads numeric value and converts to string for matching, writes as number
File doubleEnumFile = files.get(Paths
.get(output.getAbsolutePath(), "src", "Org.OpenAPITools", "Model", "DoubleEnum.cs")
.toString()
);
assertNotNull(doubleEnumFile, "Could not find file for model: DoubleEnum");
assertFileContains(doubleEnumFile.toPath(),
"reader.GetDouble().ToString()",
"writer.WriteNumberValue(",
"public static double ToJsonValue(DoubleEnum value)",
"return 1.1d;",
"return -1.2d;"
);
assertFileNotContains(doubleEnumFile.toPath(),
"reader.GetString()",
"writer.WriteStringValue(",
"return (double) value"
);
Comment on lines 282 to 339
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot test the datatype of the generated enum as well. Long and byte should have : byte or : long in them respectively...

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
openapi: 3.0.1
info:
title: Integer Enum Test
version: v1
paths:
/some/api:
get:
tags:
- Example
operationId: ExampleApi
responses:
'200':
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/IntegerEnum'
components:
schemas:
IntegerEnum:
enum:
- 0
- 1
type: integer
format: int32
x-enum-varnames:
- None
- Some
LongEnum:
enum:
- 2147483648
- 9223372036854775807
type: integer
format: int64
x-enum-varnames:
- AboveInt32Max
- Int64Max
DoubleEnum:
enum:
- 1.1
- -1.2
type: number
format: double
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,9 @@ public class AreaCodeNullableJsonConverter : JsonConverter<AreaCode?>
/// <returns></returns>
public override AreaCode? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null)
return null;

string? rawValue = reader.GetString();

AreaCode? result = rawValue == null
Expand All @@ -197,7 +200,10 @@ public class AreaCodeNullableJsonConverter : JsonConverter<AreaCode?>
/// <param name="options"></param>
public override void Write(Utf8JsonWriter writer, AreaCode? areaCode, JsonSerializerOptions options)
{
writer.WriteStringValue(areaCode.HasValue ? AreaCodeValueConverter.ToJsonValue(areaCode.Value).ToString() : "null");
if (areaCode.HasValue)
writer.WriteStringValue(AreaCodeValueConverter.ToJsonValue(areaCode.Value).ToString());
else
writer.WriteNullValue();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,9 @@ public class MarineAreaCodeNullableJsonConverter : JsonConverter<MarineAreaCode?
/// <returns></returns>
public override MarineAreaCode? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null)
return null;

string? rawValue = reader.GetString();

MarineAreaCode? result = rawValue == null
Expand All @@ -169,7 +172,10 @@ public class MarineAreaCodeNullableJsonConverter : JsonConverter<MarineAreaCode?
/// <param name="options"></param>
public override void Write(Utf8JsonWriter writer, MarineAreaCode? marineAreaCode, JsonSerializerOptions options)
{
writer.WriteStringValue(marineAreaCode.HasValue ? MarineAreaCodeValueConverter.ToJsonValue(marineAreaCode.Value).ToString() : "null");
if (marineAreaCode.HasValue)
writer.WriteStringValue(MarineAreaCodeValueConverter.ToJsonValue(marineAreaCode.Value).ToString());
else
writer.WriteNullValue();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,9 @@ public class StateTerritoryCodeNullableJsonConverter : JsonConverter<StateTerrit
/// <returns></returns>
public override StateTerritoryCode? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null)
return null;

string? rawValue = reader.GetString();

StateTerritoryCode? result = rawValue == null
Expand All @@ -169,7 +172,10 @@ public class StateTerritoryCodeNullableJsonConverter : JsonConverter<StateTerrit
/// <param name="options"></param>
public override void Write(Utf8JsonWriter writer, StateTerritoryCode? stateTerritoryCode, JsonSerializerOptions options)
{
writer.WriteStringValue(stateTerritoryCode.HasValue ? StateTerritoryCodeValueConverter.ToJsonValue(stateTerritoryCode.Value).ToString() : "null");
if (stateTerritoryCode.HasValue)
writer.WriteStringValue(StateTerritoryCodeValueConverter.ToJsonValue(stateTerritoryCode.Value).ToString());
else
writer.WriteNullValue();
}
}
}
Loading
Loading