RicoSuter/NJsonSchema

Enums and invalid characters in C#

Open

#630 opened on Feb 26, 2018

View on GitHub
 (1 comment) (0 reactions) (0 assignees)C# (550 forks)github user discovery
help wantedtype: enhancement

Repository metrics

Stars
 (1,578 stars)
PR merge metrics
 (Avg merge 39d 6h) (1 merged PR in 30d)

Description

If you have a JSON schema with a nasty enum like this one:

              "forretningshaendelse": {
                "description": "EAID_D771C875_92C1_4670_B655_23DF6D1203E2",
                "enum": [
                  "Afledt ændring",
                  "Anden ændring",
                  "Arealændring på Ejerlejlighed",
                  "Ejerlejlighed bortfaldet",
                  "Ejerlejlighed tilkommet",
                  "Arealændring på Jordstykke",
                  "BPFG med oprindelse 'Matriklen -  stedfæstet' bortfaldet",
                  "BPFG med oprindelse 'Matriklen - ikke stedfæstet' bortfaldet",
                  "BPFG med oprindelse 'Matriklen - ikke stedfæstet' tilkommet",
                  "Oprindelse for BPFG ændret til 'Matriklen - stedfæstet'",
                  "Registrering af relation fra SFE til BPFG bortfaldet",
                  "Registrering af relation fra SFE til BPFG tilkommet",
                  "Registrering af SFE som Hovedejendom for ejerlejlighedsfællesskab bortfaldet",
                  "Registrering af SFE som Hovedejendom for ejerlejlighedsfællesskab tilkommet",
                  "Noteringsændring på Jordstykke",
                  "Jordstykke(r) bortfaldet",
                  "Noteringsændring på ejendom",
                  "Jordstykke(r) tilkommet"
                ],
                "title": "forretningshaendelse",
                "type": "string"
              },

then the generated code will be invalid when using C# code generation, because the enum values will contain paranthesis () and single quotes ', which are invalid characters in C#, as these names have been copied directly from the enum as defined in JSON, where the characters are valid. The version I tested was 9.10.27.

I suggest sanitizing the input strings when decklaring the variable names to ensure that any character not allowed in C# variable names are removed. In addition, the resulting name should never be a C# keyword (I suggest adding some random number at the end if this happens). Complete lists of what is not allowed can probably be found in the C# documentation here: https://www.microsoft.com/en-us/download/confirmation.aspx?id=7029 section 2.4.2 and 2.4.3.

Obviously the property should still contain the original name.

Contributor guide