附加信息:无法转换类型为#System ;IO.MemoryStream'的对象输入' JsonData'

时间:2015-08-19 07:01:38

标签: c# json exception

我已经定义了这个类来解码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类型的异常&#39;发生在   unirest-net.dll但未在用户代码中处理

其他信息:

  

无法转换类型为System.IO.MemoryStream&#39;的对象。输入   &#39; JsonData&#39;

1 个答案:

答案 0 :(得分:2)

如何编写自己的方法而不是使用该库

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);

输出:

enter image description here