RicoSuter/NJsonSchema

Enums and invalid characters in C#

Aperta

#630 aperta il 26 feb 2018

 (1 commento) (0 reazioni) (0 assegnatari)C# (549 fork)github user discovery
help wantedtype: enhancement

Metriche repository

Star
 (1581 stelle)
Metriche merge PR
 (Merge medio 39g 6h) (1 PR mergiata in 30 g)

Descrizione

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.

Guida contributor