Reputation: 75
I am trying to deserialize JSON to C# object but not able to get rid of this compiler error. Any help would be much appreciated.
JSON
{
AX:{BX:1777}
}
Here are my deserializer classes:
Response.cs
{
public class Response
{
public AX Ax { get; set; }
}
}
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. I want to access Bx like this:
var price = response.Ax.Bx; // should return 1777
But this line produces the following compiler error:
Error: IRestResponse does not contain definition for 'Ax'
Upvotes: 0
Views: 1485
Reputation: 89
For what it's worth, and having spent some time searching around this, I would have used Newtonsoft.Json and solved it like this:
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
Upvotes: 1
Reputation: 206
Problem is with case sensitive. RestSharp serializer expects following json structure
{
Ax:{Bx:1777}
}
You have 3 ways to deal with it:
1) add DataContract and DataMember to your classes
[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
3) change your json structure
Upvotes: 0