Skip to content

[P0] Get error "Not supported type System.Text.Json.JsonElement" when serializing request #785

@erich-wang

Description

@erich-wang

Describe the issue or request

The generated code fails to serialize request content if one property is defined as object and its real type is complex object.

Detail
We have model definition as below and it property Template is defined as object:

    public partial class DeploymentProperties
    {
        /// <summary> The template content. You use this element when you want to pass the template syntax directly in the request rather than link to an existing template. It can be a JObject or well-formed JSON string. Use either the templateLink property or the template property, but not both. </summary>
        public object Template { get; set; }

        /// <summary> Name and value pairs that define the deployment parameters for the template. You use this element when you want to provide the parameter values directly in the request rather than link to an existing parameter file. Use either the parametersLink property or the parameters property, but not both. It can be a JObject or a well formed JSON string. </summary>
        public object Parameters { get; set; }
    ...
    }

The real type for Template is complex object as below:

{
  "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "storageAccountName": {
      "type": "string"
    }
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "name": "[parameters('storageAccountName')]",
      "apiVersion": "2015-06-15",
      "location": "[resourceGroup().location]",
      "properties": {
        "accountType": "Standard_LRS"
      }
    }
  ],
  "outputs": {}
}

We'll get "Not supported type System.Text.Json.JsonElement" error when running below code snippet:

            var parameters = new Deployment
            (
                new DeploymentProperties(DeploymentMode.Incremental)
                {
                    Template = JsonSerializer.Deserialize<JsonElement>(templateString)
                }
            );

            var rawResult = await DeploymentsClient.StartCreateOrUpdateAsync(groupName, deploymentName, parameters);

Describe your ideas for solutions
There're two ways to fix the issue:

  1. Deserialize the real object type for Template using extension method JsonElement.GetObject(); then we should mark JsonElementExtension as public instead of internal
  2. Update Utf8JsonWriterExtensions.WriteObjectValue to accept type JsonElement

I prefer option 2 since it is more user friendly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    v3Version 3 of AutoRest C# generator.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions