httpClient.GetAsync调用引发System.ArgumentException:无法确定JSON对象类型

时间:2019-02-06 19:59:29

标签: c# json linq

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

  

“ System.ArgumentException:无法确定JSON对象类型   类型System.Threading.Tasks.Task 1[Newtonsoft.Json.Linq.JObject].\r\n at Newtonsoft.Json.Linq.JValue.GetValueType(Nullable 1当前,Object   值)\ r \ n位于   Newtonsoft.Json.Linq.JContainer.CreateFromContent(对象内容)\ r \ n   在Newtonsoft.Json.Linq.JContainer.AddInternal(Int32 index,Object   内容,布尔值skipParentCheck)\ r \ n位于   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());
        }
    }   

不知道会发生什么,有人可以给我一些帮助吗?

2 个答案:

答案 0 :(得分:1)

您收到的立即错误是因为您没有await进行repository.ReadItemAsync<JObject>呼叫。因此,返回类型为Task<JObject>,而不是JObject

更改

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

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

话虽这么说,还有一些其他问题可能会引起问题。如果要序列化一个数组对象,然后修剪[],则在原始数组中有多个元素时,它将不再是有效的JSON。另外,将对象序列化为JSON以立即反序列化它有点奇怪,并且可能需要重新考虑。

答案 1 :(得分:0)

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

   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#,有人可以告诉我为什么会这样吗?还有其他更好的方法来解决它。