问题
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