C#更新CosmosDB时无法识别System.String[]的JSON类型如何解决
错误原因
你通过ReadItemAsync<dynamic>获取到的itemBody1本质是Newtonsoft.Json的JObject实例,不是原生C#动态对象,直接为其赋值原生System.String[]类型的数组时,Json.NET无法自动完成CLR类型到JSON类型的映射,因此抛出该错误。
解决方案
方案一:转换为JArray再赋值(改动最小)
仅需修改Aliases字段的赋值逻辑,将原生数组转换为Json.NET可识别的JArray类型即可,代码示例如下:
// 需先引入Newtonsoft.Json.Linq命名空间 using Newtonsoft.Json.Linq; String[] AliasesConverted= JSONDecoders.DecodeJSONArray(AliasesValues); // 将原生字符串数组转换为JArray后再赋值 itemBody1.Aliases = JArray.FromObject(AliasesConverted);
方案二:使用强类型模型代替dynamic(更推荐)
提前定义和CosmosDB文档结构匹配的强类型实体类,可从根本上避免运行时类型转换问题,同时获得编译期类型检查能力,代码可维护性更高:
using Newtonsoft.Json; // 定义文档对应的强类型实体 public class GuideDocument { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("GuideGuid")] public string GuideGuid { get; set; } [JsonProperty("Aliases")] public List<string> Aliases { get; set; } // 可补充其他文档字段定义 } // 调整操作代码 ItemResponse<GuideDocument> clientGuideResponse1 = await this.container.ReadItemAsync<GuideDocument>(GuideGuid, new PartitionKey(PartitionKey)); GuideDocument itemBody1 = clientGuideResponse1.Resource; String[] AliasesConverted= JSONDecoders.DecodeJSONArray(AliasesValues); itemBody1.Aliases = AliasesConverted.ToList(); GuideResponse = await this.container.ReplaceItemAsync<GuideDocument>(itemBody1, GuideGuid, new PartitionKey(PartitionKey));
内容的提问来源于stack exchange,提问作者MauMau
相关产品推荐
相关产品推荐

