【问题标题】:JsonSerializationException: Cannot deserialize the current JSON object. in asp.net coreJsonSerializationException:无法反序列化当前 JSON 对象。在 asp.net 核心中
【发布时间】:2019-06-07 16:06:06
【问题描述】:

我正在使用 asp.net core 和 cosmos db 创建一个 web api。我为获取所有项目创建了一个 api。我收到以下错误。我提供了我所有的存储库,控制器代码。请帮我找出我做错了什么??

控制器代码:

  public async Task<IActionResult> FetchListAsync(
        [FromQuery]Guid? itemId)
    {
        var result =
            await _catalogRepository.FetchListAsync(
                itemId);

        return Ok(result);
    }

存储库代码:

  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 catlog = _cosmosClient.CreateDocumentQuery<Catalog>(UriFactory.CreateDocumentCollectionUri(
            _azureCosmosDbOptions.Value.DatabaseId, "catalog"), query, feedOptions).AsEnumerable().FirstOrDefault();

            var objResponse1 =
    JsonConvert.DeserializeObject<List<Catalog>>(catlog.ToString());


            return objResponse1;
        }

错误:

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

【问题讨论】:

    标签: sql azure-cosmosdb asp.net-core-webapi


    【解决方案1】:
    var catlog = _cosmosClient.CreateDocumentQuery<Catalog>(UriFactory.CreateDocumentCollectionUri(
                _azureCosmosDbOptions.Value.DatabaseId, "catalog"), query, feedOptions).AsEnumerable().FirstOrDefault();
    

    此行返回单个对象。您正在尝试将单个对象的字符串表示解析为该对象的列表。 JsonConvert 将失败,因为它找不到要转换的对象数组,而是单个顶级 JSON 对象。

    你可以简单地返回:

    return new List<Catalog>{catlog};
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      相关资源
      最近更新 更多