【问题标题】:JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into typeJsonSerializationException:无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型
【发布时间】:2019-06-07 16:56:56
【问题描述】:

我正在开发一个 web api。我收到以下错误。相同的代码结构适用于 fetchbyid ,post,edit 。我在这里做错了什么。请帮我。 目录.cs:

  public class Catalog
    {
        [JsonProperty("id")]
        public Guid? Id { get; set; }

        [JsonProperty("VendorName")]
        public string VendorName { get; set; }

       // public List<Industy> Industy { get; set; }
        public Industy Industy { get; set; }

        public Catalog()
        {
            if (Id == null)
            {
                Id = Guid.NewGuid();
            }
            else
            {
                Id = Id;
            }

         //   this.Industy = new List<Industy>();
        }
    }



   public async Task<IEnumerable<Catalog>> FetchListAsync(
           Guid? itemId)
        {
            var feedOptions =
                  new FeedOptions
                  {
                      MaxItemCount = -1,
                      EnableCrossPartitionQuery = true
                  };
            var query = new SqlQuerySpec
            {
                QueryText = "SELECT * FROM c"

            };

            var orderDocumentQuery =
                _cosmosClient.CreateDocumentQuery<Catalog>(
                    UriFactory.CreateDocumentCollectionUri(
                        _azureCosmosDbOptions.Value.DatabaseId, "catalog"), query, feedOptions)
                    .AsDocumentQuery();

            var orderList =
                new List<Catalog>();
            Console.WriteLine(orderDocumentQuery.ToString());

            while (orderDocumentQuery.HasMoreResults)
            {
                orderList.AddRange(
                    await orderDocumentQuery.ExecuteNextAsync<Catalog>());
            }

            return orderList;
        }

错误:

JsonSerializationException:无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List`1[CatalogAPI.Entities.Industy]”,因为该类型需要 JSON 数组(例如 [1,2,3])正确反序列化。 要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其成为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像可以从 JSON 对象反序列化的数组或 List&lt;T&gt;)。 JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。 路径“Industy.Id”,第 1 行,位置 117。

我做错了什么??

【问题讨论】:

  • 能否也添加完整的Catalog 类?谢谢。
  • 已添加,请检查并帮助我先生
  • 异常错误说你必须使用public List&lt;Industy&gt; Industy,而不是public Industy Industy。无法将数组序列化为对象。
  • 可能您表中的某些项目将Industry 属性存储为对象(例如indestry: { a: 1, b: 'test '}),但也有数组具有Industry 类型的项目(例如industry: [{a: 1, b: 'test'}])。

标签: asp.net-web-api azure-cosmosdb asp.net-core-webapi


【解决方案1】:

Cosmos DB 中的 POCO 对象需要将其 id 字段设为字符串。

您需要将public Guid? Id { get; set; } 替换为public string Id { get; set; }

【讨论】:

  • 是的,它正在工作。我将返回更改为 return new List{catlog}; .谢谢你先生
猜你喜欢
  • 2016-02-05
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
相关资源
最近更新 更多