Utf8Json icon indicating copy to clipboard operation
Utf8Json copied to clipboard

Fix compilation error from generated code with readonly member and DataMemberAttribute

Open nullbus opened this issue 3 years ago • 0 comments

Hello, I had an issue with UniversalCodeGenerator.

Assume I have a struct like this:

[DataContract]
public struct Foo
{
    [DataMember(Name = "bar")]
    public readonly int Bar;

    public Foo(int Bar) => this.Bar = Bar;
}

The generated FooFormatter.Deserialize code from this struct is:

public global::Foo Deserialize(ref JsonReader reader, global::Utf8Json.IJsonFormatterResolver formatterResolver)
{
    if (reader.ReadIsNull())
    {
        throw new InvalidOperationException("typecode is null, struct not supported");
    }
    

    var __Bar__ = default(int);
    var __Bar__b__ = false;

    var ____count = 0;
    reader.ReadIsBeginObjectWithVerify();
    while (!reader.ReadIsEndObjectWithSkipValueSeparator(ref ____count))
    {
        var stringKey = reader.ReadPropertyNameSegmentRaw();
        int key;
        if (!____keyMapping.TryGetValueSafe(stringKey, out key))
        {
            reader.ReadNextBlock();
            goto NEXT_LOOP;
        }

        switch (key)
        {
            case 0:
                __Bar__ = reader.ReadInt32();
                __Bar__b__ = true;
                break;
            default:
                reader.ReadNextBlock();
                break;
        }

        NEXT_LOOP:
        continue;
    }

    var ____result = new global::Foo(__bar__); // <<<<<<<<<<< this line

    return ____result;
}

That's because ObjectSerializationInfo.GetConstructorString works different like other template code does.

This PR fixes the issue.

nullbus avatar Jul 23 '21 08:07 nullbus