Skip to content

[BUG][Csharp] Client serialization of oneOf repeats discriminator #16597

@mol-pensiondk

Description

@mol-pensiondk

Bug Report Checklist

  • Have you provided a full/minimal spec to reproduce the issue?
  • Have you validated the input using an OpenAPI validator (example)?
  • Have you tested with the latest master to confirm the issue still exists?
  • Have you searched for related issues/PRs?
  • What's the actual output vs expected output?
  • [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description

In the csharp client generator, generichost library, the JsonConverter for a class generated from a oneOf with discriminator serializes incorrectly. It will write all properties from the "inner" class plus the discriminator from the oneOf class, thus writing the discriminator property twice.

Spec and generated code here: Oneof.zip

Test that shows the error:

        [Fact]
        public void OneOfTwoSerializationTest()
        {
            var options = new JsonSerializerOptions();
            options.Converters.Add(new OneOfTwoJsonConverter());
            options.Converters.Add(new T1JsonConverter());
            options.Converters.Add(new T2JsonConverter());
            var oneOfTwo = new OneOfTwo(new T2("t2", 2), "t2");
            string json = JsonSerializer.Serialize<OneOfTwo>(oneOfTwo, options);
            Assert.DoesNotMatch("type.*type", json);
        }

The serialized json in the above:

{"$type":"t2","val":2,"$type":"t2"}
openapi-generator version

7.0.0

OpenAPI declaration file content or url

(See attached zip)

Generation Details
openapi-generator-cli generate -i Oneof.json -g csharp -o OneOfClient --package-name OneOfClient "--additional-properties=library=generichost"
Steps to reproduce

Run the test above.

Related issues/PRs

None found

Suggest a fix

The Write method of the generated OneOfTwoJsonConverter should be a lot simpler (and no WriteProperties method need be generated):

        public override void Write(Utf8JsonWriter writer, OneOfTwo oneOfTwo, JsonSerializerOptions jsonSerializerOptions)
        {
            if (oneOfTwo.T1 != null) {
                JsonSerializer.Serialize<T1>(writer, oneOfTwo.T1, jsonSerializerOptions);
                return;
            }
            if (oneOfTwo.T2 != null) {
                JsonSerializer.Serialize<T2>(writer, oneOfTwo.T2, jsonSerializerOptions);
                return;
            }
            throw new NotSupportedException();
        }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions