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

筅森魡賤 提交于 2019-12-13 13:36:17

问题


I am using 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/

Here's my RootObject class code:

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'.

Question: How can I resolve the error?


回答1:


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


来源:https://stackoverflow.com/questions/31515751/convert-the-http-response-body-to-json-format-using-unirest-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!