简体   繁体   English

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

[英]Convert the http response body to JSON format using Unirest C#

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

Here's my code: 这是我的代码:

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

I generated the RootObject class using: http://json2csharp.com/ 我使用以下命令生成了RootObject类: http ://json2csharp.com/

Here's my RootObject class code: 这是我的RootObject类代码:

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

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

When I run the above code I get the following error: 当我运行上面的代码时,我收到以下错误:

An unhandled exception of type 'System.InvalidCastException' occurred in unirest-net.dll Additional information: Unable to cast object of type 'System.IO.MemoryStream' to type 'RootObject'. unirest-net.dll中出现未处理的“System.InvalidCastException”类型异常附加信息:无法将类型为“System.IO.MemoryStream”的对象强制转换为“RootObject”。

Question: How can I resolve the error? 问题:如何解决错误?

Try this. 尝试这个。 It must be placed in an asynchronous function: 它必须放在异步函数中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM