使用Unirest C#将http响应体转换为JSON格式

时间:2015-07-20 11:49:17

标签: c# .net json unirest mashape

我正在使用mashape api:https://market.mashape.com/montanaflynn/dictionary

这是我的代码:

HttpResponse<RootObject> response = Unirest.get("https://montanaflynn-dictionary.p.mashape.com/define?word=irony")
    .header("X-Mashape-Key", "my mashape key")
    .header("Accept", "application/json")
    .asJson<RootObject>();

我使用:http://json2csharp.com/

生成了RootObject类

这是我的RootObject类代码:

class Definition
{
    public string text { get; set; }
    public string attribution { get; set; }
}

class RootObject
{
    public List<Definition> definitions { get; set; }
}

当我运行上面的代码时,我收到以下错误:

未处理的类型&#39; System.InvalidCastException&#39;发生在unirest-net.dll中 附加信息:无法转换类型为#System ;IO.MemoryStream&#39;的对象输入&#39; RootObject&#39;。

问题:如何解决错误?

1 个答案:

答案 0 :(得分:0)

试试这个。它必须放在异步函数中:

static async Task<RootObject> GetRootInfo()
{
     HttpResponse<RootObject> response = await Unirest.get("https://montanaflynn-dictionary.p.mashape.com/define?word=irony")
    .header("X-Mashape-Key", "my mashape key")
    .header("Accept", "application/json")
    .asJsonAsync<RootObject>();

     return response.Body;
}