Skip to content

[C#] Exception deserializing null for optional enum specified via reference property #4586

@szakrewsky

Description

@szakrewsky
Description

Given an object with an inline enum property "type" and a referenced enum "country", data like {"country": null} will throw an exception on deserialization, while data like {} and {"type": null} will work as expected.

Swagger-codegen version

2.2.2-SNAPSHOT

Swagger declaration file content or url
{
    "swagger": "2.0",
    "info": {
        "version": "1.0.0",
        "title": "Swagger Test"
    },
    "paths": {},
    "definitions": {
        "Address": {
            "type": "object",
            "properties": {
                "type": {
                    "type": "string",
                    "enum": [
                        "inline1",
                        "inline2"
                    ]
                },
                "country": {
                    "$ref": "#/definitions/Country"
                }
            }
        },
        "Country": {
            "type": "string",
            "enum": [
                "Ref1",
                "Ref2"
            ]
        }
    }
}
Command line used for generation

http://editor.swagger.io/#/
and
java -jar ~/swagger-codegen/modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate -i test.json -l csharp -o test/

Steps to reproduce

Generate the code. Write a sample program like:

RestResponse rsp;
Address addr;

rsp = new RestResponse();
rsp.Content = "{}";
addr = (Address)Configuration.Default.ApiClient.Deserialize(rsp, typeof(Address));
Console.WriteLine(addr.Country);

rsp = new RestResponse();
rsp.Content = "{\"type\": null}";
addr = (Address) Configuration.Default.ApiClient.Deserialize(rsp, typeof(Address));
Console.WriteLine(addr.Type);

rsp = new RestResponse();
rsp.Content = "{\"country\": null}";
addr = (Address)Configuration.Default.ApiClient.Deserialize(rsp, typeof(Address));
Console.WriteLine(addr.Country);

The first two will work, and the last will throw an exception.

Related issues

#4145 fixes the compilation issue but still doesn't work if a null is actually passed in the message.

Suggest a Fix

It seems to me that the isEnum flag is not getting set for RefProperties in DefaultCodegen.fromProperty. Could also be the case that C# needs to check for some other property in modelGeneric.mustache to know whether to force a ? reference.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions