简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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