【问题标题】:Cannot deserialize RestResponse with RestSharp C#无法使用 RestSharp C# 反序列化 RestResponse
【发布时间】:2018-10-01 05:48:44
【问题描述】:

我正在尝试将 JSON 反序列化为 C# 对象,但无法摆脱此编译器错误。任何帮助将不胜感激。

JSON

{
  AX:{BX:1777} 
}

这是我的反序列化器类:

Response.cs

{
    public class Response
    {
        public AX Ax { get; set; }
    }
}

AX.cs

{
    public class AX
    {
        public long Bx { get; set; }
    }
}

这是有问题的行:

IRestResponse<Response> response = client.Execute<Response>(request);

response.Content 一样好,并返回原始 JSON,但我希望它是 Response 类的实例。我想像这样访问 Bx:

var price = response.Ax.Bx; // should return 1777

但是这一行会产生以下编译错误:

Error: IRestResponse does not contain definition for 'Ax'

【问题讨论】:

  • 你可以试试Response response = client.Execute&lt;Response&gt;(request); 吗?通过说 IRestResponse,您正在转换为 IRestResponse 类型,并且您可能没有在 IRestResponse 接口中定义 Ax 字段。
  • 是的,但我遇到了另一个错误。
  • 我在响应类中有 Ax 字段。我认为这就是它应该在的地方。
  • 是的,这就是它需要的地方。只是浏览他们的文档(restsharp.org),看起来你需要使用RestResponse&lt;Response&gt; response = client.Execute&lt;Response&gt;(request); 而不是IRestResponse 接口。请检查这是否有帮助
  • 我也已经尝试过了。最初明确施放但徒劳无功。同样的错误仍然存​​在。

标签: c# json rest restsharp


【解决方案1】:

问题是区分大小写。 RestSharp 序列化程序需要以下 json 结构

{
  Ax:{Bx:1777} 
}

你有3种方法来处理它:

1) 将 DataContract 和 DataMember 添加到您的类中

[DataContract]
public class Response
{
    [DataMember(Name = "AX")]
    public AX Ax { get; set; }
}

[DataContract]
public class AX
{
    [DataMember(Name = "BX")]
    public long Bx { get; set; }
}

2) 编写您自己的忽略大小写敏感的序列化程序并将其与 restsharp 一起使用

3) 改变你的 json 结构

【讨论】:

    猜你喜欢
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    相关资源
    最近更新 更多