Reputation: 1961
6 years back I wrote this for RestSharp version older than 108.
But now with RestSharp Version 108 I am unable to use the same as I am getting an error as
Could not load type 'RestSharp.Deserializers.DeserializeAsAttribute' from assembly 'RestSharp, Version=108.0.1.0, Culture=neutral, PublicKeyToken=598062e77f915f75'.
My JSON Payload is as:
{
"agentType": "Sub Broker",
"agentCode": "FWM",
"agentName": "FWM",
"default": "Y"
}
In my c# Class I have this; Note that default is a reserved word, hence I made it as "IsDefault" mapped to the correct attribute name using DeserializeAsAttribute
from RestSharp Version prior to 108:
public class AgentInformation
{
public string agentType { get; set; }
public string agentCode { get; set; }
public string agentName { get; set; }
[DeserializeAs(Name = "default")]
public string isDefault { get; set; }
}
I am calling the API from RestSharp Version 108 as:
try
{
var client = new RestClient("https://xxxx.io/v3/xxxxxxx");
var request = new RestRequest();
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = client.Get<AgentInformation>(request);
var data = response;
Console.ReadLine();
}
catch (Exception er)
{
throw er;
}
Update:
As @jhambright suggested in his comment, I used System.Text.Json
in the following way and it worked.
Note here, System.Text.Json
offers JsonPropertyName
public class AgentInformation
{
public string agentType { get; set; }
public string agentCode { get; set; }
public string agentName { get; set; }
[JsonPropertyName("default")]
public string isDefault { get; set; }
}
Then in my code I did the following way:
try
{
var client = new RestClient("https://xxx.xxx.io/v3/xxxx-xxx-xxxx-xxx-xxxxx");
//client.AddDefaultHeader("application/json", () => new RestSharp.Serializers.Newtonsoft.Json.NewtonsoftJsonSerializer());
var request = new RestRequest();
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = await client.GetAsync(request);
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
var data = JsonSerializer.Deserialize<Model.AgentInformation>(response.Content, options);
Console.WriteLine(data.agentInformation.isDefault);
}
catch (Exception er)
{
throw er;
}
This resource here also helped me.
Upvotes: 1
Views: 302
Reputation: 204
I believe RestSharp is now using System.Text.Json
for default json deserialization. You should be able to use [JsonPropertyName("default")]
attribute to direct the deserializer.
Upvotes: 3