简体   繁体   English

无法使用 RestSharp C# 反序列化 RestResponse

[英]Cannot deserialize RestResponse with RestSharp C#

I am trying to deserialize JSON to C# object but not able to get rid of this compiler error.我正在尝试将 JSON 反序列化为 C# 对象,但无法摆脱此编译器错误。 Any help would be much appreciated.任何帮助将非常感激。

JSON JSON

{
  AX:{BX:1777} 
}

Here are my deserializer classes:这是我的反序列化器类:

Response.cs响应.cs

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

AX.cs AX.cs

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

Here is the line that is problematic:这是有问题的行:

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

response.Content is just as fine and returns the raw JSON but I want it to be an instance of the Response class. response.Content 一样好,并返回原始 JSON,但我希望它是 Response 类的一个实例。 I want to access Bx like this:我想像这样访问 Bx:

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

But this line produces the following compiler error:但是这一行会产生以下编译器错误:

Error: IRestResponse does not contain definition for 'Ax'

Problem is with case sensitive.问题是区分大小写的。 RestSharp serializer expects following json structure RestSharp 序列化程序需要以下 json 结构

{
  Ax:{Bx:1777} 
}

You have 3 ways to deal with it:你有3种方法来处理它:

1) add DataContract and DataMember to your classes 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) write your own serializer that ignores case sensitive and use it with restsharp 2)编写您自己的忽略大小写敏感的序列化程序并将其与restsharp一起使用

3) change your json structure 3)改变你的json结构

For what it's worth, and having spent some time searching around this, I would have used Newtonsoft.Json and solved it like this:对于它的价值,并且花了一些时间搜索这个,我会使用 Newtonsoft.Json 并像这样解决它:

IRestResponse response = client.Execute(request);
string ResponseStr = response.Content.ToString();
dynamic Response = JsonConvert.DeserializeObject<dynamic>(ResponseStr);

you can then call off the elements as you need them:然后,您可以根据需要取消元素:

var price = Response.AX.BX;
string Description = Response.AX.Desc.ToString();     etc

Hope this helps someone希望这可以帮助某人

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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