Skip to content

Commit

Permalink
fix: newtonsoft could not handle enum values (#1731)
Browse files Browse the repository at this point in the history
  • Loading branch information
jonaslagoni authored Jan 15, 2024
1 parent 8ca9004 commit 8787210
Show file tree
Hide file tree
Showing 7 changed files with 91 additions and 25 deletions.
5 changes: 2 additions & 3 deletions src/generators/csharp/presets/NewtonsoftSerializerPreset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ function renderSerialize({ model }: { model: ConstrainedObjectModel }): string {
var stringEnumValue = enumValue.ToString();
// C# converts booleans to uppercase True and False, which newtonsoft cannot understand
var jsonStringCompliant = stringEnumValue == "True" || stringEnumValue == "False" ? stringEnumValue.ToLower() : stringEnumValue;
var jsonToken = JToken.Parse(jsonStringCompliant);
jo.Add("${prop.unconstrainedPropertyName}", jsonToken);`;
jo.Add("${prop.unconstrainedPropertyName}", JToken.FromObject(jsonStringCompliant, serializer));`;
}
return `if (value.${propertyAccessor} != null)
{
Expand Down Expand Up @@ -93,7 +92,7 @@ function renderDeserialize({
prop.property instanceof ConstrainedReferenceModel &&
prop.property.ref instanceof ConstrainedEnumModel
) {
toValue = `${prop.property.name}Extensions.To${prop.property.name}(jo["${prop.unconstrainedPropertyName}"])`;
toValue = `${prop.property.name}Extensions.To${prop.property.name}(jo["${prop.unconstrainedPropertyName}"].ToString())`;
}
return `if(jo["${prop.unconstrainedPropertyName}"] != null) {
value.${propertyAccessor} = ${toValue};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ if(jo[\\"numberProp\\"] != null) {
value.NumberProp = jo[\\"numberProp\\"].ToObject<double?>(serializer);
}
if(jo[\\"enumProp\\"] != null) {
value.EnumProp = EnumTestExtensions.ToEnumTest(jo[\\"enumProp\\"]);
value.EnumProp = EnumTestExtensions.ToEnumTest(jo[\\"enumProp\\"].ToString());
}
if(jo[\\"objectProp\\"] != null) {
value.ObjectProp = jo[\\"objectProp\\"].ToObject<NestedTest?>(serializer);
Expand Down Expand Up @@ -88,8 +88,7 @@ if (value.EnumProp != null)
var stringEnumValue = enumValue.ToString();
// C# converts booleans to uppercase True and False, which newtonsoft cannot understand
var jsonStringCompliant = stringEnumValue == \\"True\\" || stringEnumValue == \\"False\\" ? stringEnumValue.ToLower() : stringEnumValue;
var jsonToken = JToken.Parse(jsonStringCompliant);
jo.Add(\\"enumProp\\", jsonToken);
jo.Add(\\"enumProp\\", JToken.FromObject(jsonStringCompliant, serializer));
}
if (value.ObjectProp != null)
{
Expand Down
4 changes: 3 additions & 1 deletion test/runtime/generic-input.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@
"type": "string"
}
}
},
"enumTest": {
"enum": ["test", "test2"]
}
},
"patternProperties": {
Expand All @@ -52,7 +55,6 @@
}
},
"required": [
"street_name",
"house_number",
"array_type"
]
Expand Down
52 changes: 39 additions & 13 deletions test/runtime/runtime-csharp.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,43 @@
import { CSHARP_JSON_SERIALIZER_PRESET, CSharpFileGenerator } from '../../';
import { CSHARP_JSON_SERIALIZER_PRESET, CSHARP_NEWTONSOFT_SERIALIZER_PRESET, CSharpFileGenerator } from '../../';
import path from 'path';
import input from './generic-input.json';

const generator = new CSharpFileGenerator({
presets: [CSHARP_JSON_SERIALIZER_PRESET]
});
async function generateJsonSerializer() {
const generator = new CSharpFileGenerator({
presets: [CSHARP_JSON_SERIALIZER_PRESET]
});

await generator.generateToFiles(
input,
path.resolve(
// eslint-disable-next-line no-undef
__dirname,
'./runtime-csharp/runtime-csharp/src/models/json_serializer'
),
{ namespace: 'com.mycompany.app.json_serializer' }
);
}
async function generateNewtonsoft() {
const generator = new CSharpFileGenerator({
presets: [CSHARP_NEWTONSOFT_SERIALIZER_PRESET]
});
await generator.generateToFiles(
input,
path.resolve(
// eslint-disable-next-line no-undef
__dirname,
'./runtime-csharp/runtime-csharp/src/models/newtonsoft'
),
{ namespace: 'com.mycompany.app.newtonsoft' }
);
}

generator.generateToFiles(
input,
path.resolve(
// eslint-disable-next-line no-undef
__dirname,
'./runtime-csharp/runtime-csharp/src/models/json_serializer'
),
{ namespace: 'com.mycompany.app.generic' }
);
async function generateEverything() {
await Promise.all(
[
generateJsonSerializer(),
generateNewtonsoft()
]
)
}
generateEverything();
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<PackageReference Include="NUnit3TestAdapter" Version="4.2.1" />
<PackageReference Include="NUnit.Analyzers" Version="3.3.0" />
<PackageReference Include="coverlet.collector" Version="3.1.2" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

<ItemGroup>
Expand All @@ -24,6 +25,7 @@
<None Remove="src\models\json_serializer\" />
<None Remove="test\models\" />
<None Remove="test\models\json_serializer\" />
<None Remove="Newtonsoft.Json" />
</ItemGroup>
<ItemGroup>
<Folder Include="src\" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using System.Text.Json;
using com.mycompany.app.generic;
using System.Text.Json;
using com.mycompany.app.json_serializer;

namespace runtime_csharp;
namespace runtime_csharp.json_serializer;

public class AddressTests
{
Expand All @@ -18,13 +18,16 @@ public void TestSerializingFullModel()
NestedObject nestedObject = new NestedObject();
nestedObject.Test = "test";
address.NestedObject = nestedObject;
address.StreetName = "test";
address.Marriage = true;
address.Members = 2;
address.HouseNumber = 1;
address.ArrayType = new dynamic[] { 1, "test" };
address.EnumTest = EnumTest.TEST;
address.AdditionalProperties = new Dictionary<string, dynamic>();
address.AdditionalProperties.Add("test_not_used", 2);

string actualJsonString = JsonSerializer.Serialize(address);
string expectedJsonString = "{\"street_name\":\"test\",\"house_number\":1,\"marriage\":true,\"members\":2,\"array_type\":[1,\"test\"],\"nestedObject\":{\"test\":\"test\"}}";
string expectedJsonString = "{\"house_number\":1,\"marriage\":true,\"members\":2,\"array_type\":[1,\"test\"],\"nestedObject\":{\"test\":\"test\"},\"enumTest\":\"test\",\"test_not_used\":2}";
Assert.That(actualJsonString, Is.EqualTo(expectedJsonString));
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System.Text.Json;
using com.mycompany.app.newtonsoft;
using Newtonsoft.Json;

namespace runtime_csharp.newtonsoft;

public class AddressTests
{

[SetUp]
public void Setup()
{
}

[Test]
public void TestSerializingFullModel()
{
Address address = new Address();
NestedObject nestedObject = new NestedObject();
nestedObject.Test = "test";
address.NestedObject = nestedObject;
address.Marriage = true;
address.Members = 2;
address.HouseNumber = 1;
address.ArrayType = new dynamic[] { 1, "test" };
address.EnumTest = EnumTest.TEST;
address.AdditionalProperties = new Dictionary<string, dynamic>();
address.AdditionalProperties.Add("test_not_used", 2);

string actualJsonString = JsonConvert.SerializeObject(address);
string expectedJsonString = "{\"house_number\":1.0,\"marriage\":true,\"members\":2,\"array_type\":[1,\"test\"],\"nestedObject\":{\"test\":\"test\"},\"enumTest\":\"test\",\"test_not_used\":2}";
Assert.That(actualJsonString, Is.EqualTo(expectedJsonString));
}
}

0 comments on commit 8787210

Please sign in to comment.