【问题标题】:Convert the http response body to JSON format using Unirest C#使用 Unirest C# 将 http 响应正文转换为 JSON 格式
【发布时间】:2015-10-09 12:45:38
【问题描述】:

我正在使用 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>();

我使用 http://json2csharp.com/ 生成了 RootObject 类

这是我的 RootObject 类代码:

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

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

当我运行上述代码时,出现以下错误:

unirest-net.dll 中出现“System.InvalidCastException”类型的未处理异常 附加信息:无法将“System.IO.MemoryStream”类型的对象转换为“RootObject”类型。

问题:我该如何解决这个错误?

【问题讨论】:

    标签: c# .net json unirest mashape


    【解决方案1】:

    试试这个。必须放在异步函数中:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 2023-04-01
      • 2017-07-20
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多