Skip to content

[Feat]: Support Literal Type Model Property #3035

@archerzz

Description

@archerzz

Description

Part of #2972 For CADL model with literal property like below:

model Foo {
  name: string;
  type: "accepted"
}

We will generate the model codes like:

public class Foo
{
        internal Foo(string name)
        {
            Argument.AssertNotNull(name, nameof(name));

            Name = name;
            Type = "accepted";
        }

        /// <summary> Gets the name. </summary>
        public string Name { get; }
        /// <summary> Gets the age. </summary>
        internal string Type { get; }
    }

    void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("name");
            writer.WriteStringValue(Name);
             writer.WritePropertyName("type");
            writer.WriteStringValue(Type);
            writer.WriteEndObject();
        }
        internal static Foo DeserializeFoo(JsonElement element)
        {
            string name = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
            }
            return new Foo(name);
        }

        /// <summary> Deserializes the model from a raw response. </summary>
        /// <param name="response"> The response to deserialize the model from. </param>
        internal static Foo FromResponse(Response response)
        {
            using var document = JsonDocument.Parse(response.Content);
            return DeserializeThing(document.RootElement);
        }
}
  • the property doesn't show up in the constructor parameter list, but it's initialized in constructor
  • the property is read-only
  • the property is internal

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions