CosmosDB Update c#: Could not determine JSON object type for type System.String[]

Viewed 157

I want to update a field in CosmosDB to array like below:

"Aliases": [ "John", "Johnny" ],

Below is my code:

           dynamic GuideDoc= new
           {
               id = "00B2845F-F394-5E93-9A26-E70000452562",
               type = "Guide",
               GuideGuid= "00B2845F-F394-5E93-9A26-E70000452562"
           };

           ItemResponse<dynamic> clientGuideResponse1 = await this.container.ReadItemAsync<dynamic>(GuideGuid, new PartitionKey(PartitionKey));
           dynamic itemBody1 = clientGuideResponse1.Resource;

           String[] AliasesConverted= JSONDecoders.DecodeJSONArray(AliasesValues);
           itemBody1.Aliases= AliasesConverted;

           GuideDoc= itemBody1;

           GuideResponse = await this.container.ReplaceItemAsync<dynamic>(GuideDoc, GuideGuid, new PartitionKey(PartitionKey));

The part that stores the data to itemBody1.Aliases is returning an error "Could not determine JSON object type for type System.String[]"

How do I make it save the value to Aliases as an array?

1 Answers

The easiest way to add new properties while keeping everything else intact is deserializing it into a Dictionary. As example:

var response = await container.ReadItemAsync<Dictionary<string, object>>(id, partitionKey);
var item = response.Resource;
item["Aliases"] = new[] { "John", "Johnny" };
await container.ReplaceItemAsync(item, id, partitionKey);

The reason it doesn't work is because the deserializer will return the result as JObject when you use dynamic as type. You can't navigate the JObject through the properties as if it were deserialized into a class with properties. The error you describe is a bit different than I would have thought though.

Related