【问题标题】:httpClient.GetAsync call throw System.ArgumentException: Could not determine JSON object typehttpClient.GetAsync 调用抛出 System.ArgumentException:无法确定 JSON 对象类型
【发布时间】:2019-02-06 19:59:28
【问题描述】:

我尝试通过 httpClient.GetAsync 调用 get api。但我得到了例外

"System.ArgumentException: 无法确定 JSON 对象类型 类型 System.Threading.Tasks.Task1[Newtonsoft.Json.Linq.JObject].\r\n at Newtonsoft.Json.Linq.JValue.GetValueType(Nullable1 当前,对象 值)\r\n 在 Newtonsoft.Json.Linq.JContainer.CreateFromContent(对象内容)\r\n 在 Newtonsoft.Json.Linq.JContainer.AddInternal(Int32 索引,对象 内容,布尔型 skipParentCheck)\r\n at MediaIngestionSFSvc.Controllers.MediaIngestionController.d__2.MoveNext()"

这是我尝试调用的 api

public IActionResult GetSKUByEditionDisplayName(string edition)
    {
        string message = null;
        try
        {
            if (string.IsNullOrEmpty(edition))
            {
                message = $"Edition is null";
                throw new ArgumentNullException(message);
            }

            SqlQuerySpec sqlQuery = repository.GenerateQuery(CollectionName, new KeyValuePair<string, object>(Enums.id.ToString(), MediaRefreshConstants.SKUtoEditionTable));
            IEnumerable<JObject> docs = repository.ReadItemAsync<JObject>(sqlQuery);

            if (!docs.Any())
            {
                message = $"No SKUtoEditionTable found in Cosmos db";
                throw new NullReferenceException(message);
            }

            string responseBody = JsonConvert.SerializeObject(docs);
            string jsonObject = responseBody.Trim().Trim('[', ']');
            JObject responseObject = JObject.Parse(jsonObject);

            if (responseObject[edition] == null)
            {
                message = $"No Edition {edition} found in SKUtoEditionTable";
                throw new NullReferenceException();
            }

            string sku = responseObject[edition].ToString();
            return CreateActionResult(HttpStatusCode.OK, sku);

        } catch (Exception e) when (e is ArgumentNullException || e is NullReferenceException)
        {
            message = $"Fail to retrieve sku from EditionToSKUTypeMapping table";
            return CreateActionResult(HttpStatusCode.BadRequest, e.ToString());
        } catch (Exception ex)
        {
            message = $"Fail to retrieve sku from EditionToSKUTypeMapping table";
            return CreateActionResult(HttpStatusCode.InternalServerError, ex.ToString());
        }
    }   

不知道怎么回事,谁能帮帮我?

【问题讨论】:

    标签: c# json linq


    【解决方案1】:

    您收到的直接错误是因为您没有 await 调用 repository.ReadItemAsync&lt;JObject&gt;。所以返回类型是Task&lt;JObject&gt;,而不是JObject

    改变

    IEnumerable<JObject> docs = repository.ReadItemAsync<JObject>(sqlQuery);
    

    IEnumerable<JObject> docs = await repository.ReadItemAsync<JObject>(sqlQuery);
    

    话虽如此,还有一些额外的事情可能会导致问题。如果您正在序列化一个数组对象,然后修剪掉[],如果原始数组中有多个元素,则它不再是有效的 JSON。此外,将对象序列化为 JSON 以立即反序列化它有点奇怪,可能需要重新考虑。

    【讨论】:

    • 即使方法是readItemAsync,也不是异步方法。我最后返回的不是文档。我返回一个 sku 字符串。
    • 如果它不是异步方法,那么它不应该这样命名。这是可读性和可用性非常差的形式。
    【解决方案2】:

    我通过这种方式解决了这个问题: 这是原来的逻辑: 公共异步任务 A(字符串 uri,字符串 contentType) { HttpResponseMessage httpResponseMessage = 等待 httpClient.GetAsync(uri); 返回http响应消息; }

       private async Task<string> B(string edition)
        {
    
            HttpResponseMessage keyValueResponse = await new HttpHelper().A(keyPairUrl, JsonContentTypeHeaderValue);
            string responseBody = await keyValueResponse.Content.ReadAsStringAsync();
            return responseBody.Trim();
        }
    
      private async<JObject> C() {
       JObject object = new JObject();
    object["s"] = await B(some string);
    return object;
    }
    

    它会抛出上述异常: 但是如果我改变 await B(somestring);到 B(somestring).Result; 问题将消失。

    我很适合 c#,有人能告诉我为什么会这样吗?有没有其他更好的解决方法。

    【讨论】:

      猜你喜欢
      • 2015-01-18
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多