使用Unirest C#将http响应正文转换为JSON格式 [英] Convert the http response body to JSON format using Unirest C#

查看:317
本文介绍了使用Unirest C#将http响应正文转换为JSON格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using 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>();

我使用以下方法生成了RootObject类: http://json2csharp.com/

I generated the RootObject class using: http://json2csharp.com/

这是我的RootObject类代码:

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:

unirest-net.dll中发生了'System.InvalidCastException'类型的未处理异常 其他信息:无法将类型为"System.IO.MemoryStream"的对象转换为类型为"RootObject".

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

问题:如何解决该错误?

推荐答案

尝试一下.它必须放在异步函数中:

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

这篇关于使用Unirest C#将http响应正文转换为JSON格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆