【问题标题】:Additional information: Unable to cast object of type 'System.IO.MemoryStream' to type 'JsonData'附加信息:无法将“System.IO.MemoryStream”类型的对象转换为“JsonData”类型
【发布时间】:2015-08-19 07:01:37
【问题描述】:

我已经定义了这个类来解码 json 响应

      private class JsonData
      {
        [JsonProperty(PropertyName = "api-author")]
        public string apiauthor { get; set; }
        [JsonProperty(PropertyName = "api-usage")]
        public string apiusage { get; set; }
        [JsonProperty(PropertyName = "status")]

        public string status { get; set; }
        [JsonProperty(PropertyName = "language")]
        public string language { get; set; }

        [JsonProperty(PropertyName = "sentiment-text")]
        public string sentimenttext { get; set; }
        [JsonProperty(PropertyName = "sentiment-score")]
        public string sentimentscore { get; set; }
    }

我正在尝试调用 api

string url = "https://loudelement-free-natural-language-processing-service.p.mashape.com/nlp-text/?text=";

            var response = Unirest.get(url)
           .header("X-Mashape-Key", "AlZVYH30C9mshLPNM7KiE48aFfTHp1h3A31jsnmVPccxBzW5uB")
           .header("Accept", "application/json")
           .asJson<JsonData>()
           .Body
           ;

            var status = response.sentimenttext;

我在哪里得到这个异常

System.InvalidCastException' 类型的异常发生在 unirest-net.dll 但未在用户代码中处理

补充资料:

无法将“System.IO.MemoryStream”类型的对象转换为类型 'JsonData'。

【问题讨论】:

  • 通过调用 mashape api 收到的 asjson 响应..
  • 好的,让我澄清一下。 asJson 中的代码是什么样的?它有什么作用?它返回什么?
  • asjson 正在返回“api-author”:“Taewook Kang (taewook.kang@gmail.com)”、“api-usage”:“完全免费,只要你在你的某个地方给我信用website.", "status": "OK", "language": "english", "sentiment-text": "negative", "sentiment-score": "-0.171441"
  • 可以发asJson的代码吗?
  • 一旦我发现您使用的是第 3 方库,我就查看了 Unirest 的代码,我会远离这个库,因为它会造成潜在的死锁,因为它使用阻塞异步代码。我不明白为什么它会抛出那个特定的异常,但是如果您的代码都没有尝试将流大小写为 JsonData,那么可以肯定地说该库中有一些失败的假设。

标签: c# json exception


【解决方案1】:

编写自己的方法而不是使用那个库怎么样

public async Task<T> Get<T>(string url)
{
    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.TryAddWithoutValidation("X-Mashape-Key", "AlZVYH30C9mshLPNM7KiE48aFfTHp1h3A31jsnmVPccxBzW5uB");
        client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json");
        var json = await client.GetStringAsync(url);
        return JsonConvert.DeserializeObject<T>(json);
    }
}

现在你可以把它称为

string url =  "https://loudelement-free-natural-language-processing-service.p.mashape.com/nlp-text/?text=apple";
var jsonData = await Get<JsonData>(url);

输出:

【讨论】:

  • 当我添加这段代码时,我得到错误 Error 1 'await' 运算符只能在异步方法中使用。考虑使用“async”修饰符标记此方法并将其返回类型更改为“Task”。
  • async 关键字添加到您的方法中。例如,请参见 `Get` 方法。
  • 我正在尝试在同步方法中调用此异步方法并收到错误错误“'await' 运算符只能在异步方法中使用。考虑使用 'async' 修饰符和将其返回类型更改为“任务”。”
  • “如何编写自己的方法而不是使用那个库”。这怎么可能是解决方案?我希望我不需要解释您为什么要使用库而不是编写自己的代码...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-19
相关资源
最近更新 更多